Saving remote image to assets field in entry I'm working on importing entries from EE to Craft. I started with the craftimport plugin, and I am expanding it to do a bit more. One of the things I need is to save an image from a remote URL into an entry's assets field.

So far I've only managed to save it to disk, and then I can go into Craft admin and index the assets folder, and re-run the import, which will save the relation between the image and the entry using this:

$command = craft()-&gt;db-&gt;createCommand();
$imgRecord = $command
            -&gt;select('id')
            -&gt;from('assetfiles')
            -&gt;where(array("AND", "filename='" . $images[0]['filename'] . "'", "folderId=2"))
            -&gt;queryRow();

if ($imgRecord['id']) {
    $imgFieldRecord = FieldRecord::model()-&gt;findByPk($imgFieldId);
    $imgFieldModel = FieldModel::populateModel($imgFieldRecord);
    craft()-&gt;relations-&gt;saveRelations($imgFieldModel, $entryModel, array($imgRecord['id']));
}


So I'm wondering if it's possible to do this whole thing in one run instead of two? I guess the only thing the indexing does is look for images and store them in the database. But I can't seem to find anything in the documentation that tells me how to do it.
Your best bet to get the image in as an Asset in one go would be to use 

$response = craft()-&gt;assets-&gt;insertFileByLocalPath($fileLocation, $fileName, $targetFolderId, AssetConflictResolution::KeepBoth);



$fileLocation would be the file's location on the disk
$fileName is the desired file name
$targetFolderId is the Assets folder, obviously. Look it up in craft_assetfolders table
The last argument is how to resolve any naming conflicts.


This will return an AssetOperationResponseModel object.

$fileId = $response-&gt;getDataItem('fileId');


This will get you the file Id. For an in-action example, see AssetsController::actionExpressUpload()

Note: This will copy the file to the location. This method is intended for importing a file into an Assets source from a different location, say, a temporary folder. It will probably work alright if the file is already in it's intended place, but I still feel like I need to warn you about this

You can also use this to import images to external sources, by the way.