2

I'm looking for the correct way to import an image from a url and save it to an entry and in the correct subfolder (uploads/images/{id})

I've created a resource pointing to uploads/images and the entry field will upload to resource/{id} by default.

As I understand the file also needs to be indexed in the database for it to be visible in the file browser so I can't just save it straight to the file system.

5

Here's how I did it in a recent project:

    $fileIds = array();

    // get remote image and store in temp path
    $imageInfo = pathinfo($data['image_url']);
    $tempPath = CRAFT_STORAGE_PATH . 'runtime/temp/' . $imageInfo['basename'];
    file_put_contents($tempPath, fopen($data['image_url'], 'r'));

    // insert the file into assets
    $response = craft()->assets->insertFileByLocalPath(
      $tempPath,
      $imageInfo['basename'],
      $myAssetFolderId, // notice, this is the id of the folder you want to upload to
      AssetConflictResolution::KeepBoth
    );

    // if the response is a success, get the file id
    if ($response && $response->isSuccess()) {
        $fileIds[] = $response->getDataItem('fileId');
    }

    // create a new entry
    $entry = new EntryModel();
    $entry->sectionId = $mySectionId;
    $entry->typeId = $myEntryTypeId;
    $entry->authorId = 1;

    // set your content, including image field by id
    $entry->getContent()->title = $data['title'];
    $entry->getContent()->mainImage = $fileIds;

    $success = craft()->entries->saveEntry($entry);

I included the entry saving part of it to show how the response is used to get the file id(s) and so on.

Whether this is the "correct" way to do it or not, I don't know. :)

| improve this answer | |
  • 1
    It's correct if it works. ;) – Brad Bell Sep 25 '15 at 22:30
  • Thanks, could you help me getting the folder id and resource id – HTDutchy Oct 1 '15 at 7:20
  • Sorry for reviving this, but in my case, I had to change $fileIds[] = $response->getDataItem('fileId'); to $fileIds[] = $response->getResponseData(); because it was giving me an error when saving because the filename was empty. – Jorge Anzola Jun 15 '17 at 11:03

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.