Importing images from external url and saving to entry using plugin 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.
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()-&gt;assets-&gt;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 &amp;&amp; $response-&gt;isSuccess()) {
        $fileIds[] = $response-&gt;getDataItem('fileId');
    }

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

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

    $success = craft()-&gt;entries-&gt;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. :)