2

I've created several entries from a feed from the eBay API, but I would like to add images to the entry too!

I've managed to get an array of URLs, which I would like to import into an assets field that I have on the new entries.

I saw a post from Brandon from a couple years back suggesting it was not possible to do this, unable to find anything more up-to-date.

Could I grab the image with cURL in my plugin then create a new AssetFileModel and some how sync the temp image file with Craft somehow? As a follow up question how would I add multiple images to the assets field on my new entry?

Thanks Joe

1 Answer 1

5

Download the image into a temp file, then upload it as an asset. You can find $iAssetSourceId by looking at the URL when editing an asset source

$iAssetSourceId = 4;
$iAssetFolderId = (int)craft()->assets->getRootFolderBySourceId($iAssetSourceId)->id;
$sTempFilePath = sys_get_temp_dir() . DIRECTORY_SEPARATOR . $sFilename;
$sFileContents = file_get_contents($sImageUrl);
file_put_contents($sTempFilePath, $sFileContents);

// Get craft to copy the temp file into the assets folder
$oAssetOperationResponse = craft()->assets->insertFileByLocalPath(
    $sTempFilePath,
    $sFilename,
    $iAssetFolderId,
    AssetConflictResolution::Replace
);

return (int)$oAssetOperationResponse->responseData["fileId"];
3
  • 1
    I would recommend to use the AssetsHelper::getTempFilePath($extension); helper for the temporary file path.
    – carlcs
    May 12, 2016 at 12:35
  • 1
    Any idea what the equivalent of craft()->assets->insertFileByLocalPath() is for Craft 3?
    – SteveEdson
    Jun 25, 2017 at 10:20
  • 2
    It seems Craft 3 does use insertFileByLocalPath. I was able to handle this by simply creating a new Asset element and saving it. When doing so, you just need to set the tempFilePath property of the element to the path you put the file to in the beginning. i.e. $asset = new Asset(); $asset->tempFilePath = $sTempFilePath; $asset->setScenario(Asset::SCENARIO_CREATE); Craft::$app->getElements()->saveElement($asset); You'll also want to set a few other properties such as filename, folderId, & volumeId. Mar 3, 2018 at 19:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.