Since this snippet includes a lot of information the title is simply a bunch of keywords. Basically we are using file uri to determine if it exists and is managed or needs to be saved as new managed file. Then use "entity_metadata_wrapper" to save the field to entity. This example is from migration of files from another Drupal installation.
Source code viewer
$uri = file_stream_wrapper_uri_normalize($uri); } else { $file = new StdClass(); $file->uri = $uri; $file->uid = 0; $file->filemime = file_get_mimetype($uri); $file->status = FILE_STATUS_PERMANENT; $file = file_save($file); } $wrapper = entity_metadata_wrapper('node', $node); }Programming Language: PHP