I wish to add a file in the filesystem to file_managed (if its not already there), so that it can then be attached to a field.

file_save() can be used, but one needs to check if the file is already in file_managed, otherwise file_save() will blow up :
PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'public://myfile.jpg' for key 'uri': INSERT INTO {file_managed} (uid ...

The first idea was to use file_load() and if that returns false, then do file_save(). But file_load() searches by fid, and we dont yet have that.

    $picturepath='iamges';
    $file = new stdClass();
    $file->uid = $node->uid;
    $file->filename = 'myfile.jpg';
    $file->uri = file_build_uri($picturepath);
    $file->filemime = file_get_mimetype('/var/www/sites/default/files/' . $picturepath);
    $file->status = '1';
    $savedFile=file_load($file);       <<== Always is false
     if (!$savedFile) {
       dpm('File not yet in db, so file_save');
       //$savedFile = file_save($file);    <<== blows up on the second run. Website crashes.
    }else{
     dpm('We already have the file registered in the DB');
     // now attach the image to the field in our node
     $newnode->field_ideaimage['und'][0] = $savedFile;
     field_attache_update('node' $newnode);
   }

Thanks in advance for any tips...

Comments

dpovshed’s picture

Hey boran!

What you need to use here is the code fragment like:

// Lookup for file named IMG_06032012_114038.png ...
$files = entity_load('file', FALSE, array('filename' => 'IMG_06032012_114038.png'));
dpm($files);
if (empty($files)) {
  // Such file does not exists,
  // add it and use then
  ...
}
else {
  // we already have file loaded.
  // in array we may find the file id and file URI

  // if we need extra care: formally we may have several files with the same name, and 
  // also there is a chance that user loaded this to private area. In most cases this is does not matter and
  // we can just use first element of array for our purpose:
  $file_object = reset($files);
  dpm($file_object);
}

Hope this helps, let me know if you need any further assistance!

boran’s picture

Status: Active » Closed (fixed)

Excellent tip. Thanks a million.