1

I need to be able to side load an image and attach to an entry.

My image is coming from an external url... such as http://someplace.com/image.jpg - i can store this in a temporary file so its locally accessible. But then how do I upload this image (without using $_POST or $_FILES) and attach to an entry.

The method i'm trying at the moment i'm using something like: uploadNewAsset(UploadedFile $uploadedFile, $folderId)

But UploadedFile seems to only want to accept POST variables, unless i'm missing something

Any help would be great

Thanks

1

You can see an entire example how to fetch a file via curl, save it into an asset and relate it to an entry here

// get the entries service
$entries = Craft::$app->getElements();

// get the entry
$entry = \craft\elements\Entry::find()->one();

// somehow grab the path of your image
$client = Craft::createGuzzleClient();
$response = $client->get('https://www.google.com/logos/2018/halloween18/rc5/cta.png');

$image = $response->getBody()->getContents();
$path = Craft::$app->getPath()->getTempPath() . DIRECTORY_SEPARATOR  . 'someFile.png';
FileHelper::writeToFile($path, $image);

// the folder for the image
$folder = Craft::$app->getAssets()->getFolderById(1);

// create a new asset
$asset = new \craft\elements\Asset();
$asset->tempFilePath = $path;
$asset->filename = 'someFileName.jpg';
$asset->title = 'someTitle';
$asset->newFolderId = $folder->id;
$asset->volumeId = $folder->volumeId;
$asset->avoidFilenameConflicts = true;
$asset->setScenario(\craft\elements\Asset::SCENARIO_CREATE);
if($entries->saveElement($asset) === true){
    // file was saved 
    $entry->setFieldValue('assetFieldHandle', [$asset->id]);
    $entries->saveElement($entry);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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