Uploading and saving a file programmatically to Drupal nodes

Kevin picture Kevin · Sep 13, 2011 · Viewed 25.3k times · Source

I am trying to create a node based on a custom form submission. Everything works great except for the images that get uploaded.

I can capture them fine and set them in the form object cache. When I pass the data into the function to create the node, I get this error:

"The specified file could not be copied, because no file by that name exists. Please check that you supplied the correct filename."

I also receive the error multiple times, despite only submitting one or two images at a time.

Here is the code I am using. $uploads is passed in and is an array of file objects returned from file_save_upload() in a previous step:

if (isset($uploads)) {
    foreach ($uploads as $upload) {
      if (isset($upload)) {
        $file = new stdClass;
        $file->uid = 1;
        $file->uri = $upload->filepath;
        $file->filemime = file_get_mimetype($upload->uri);
        $file->status = 1;  

        $file = file_copy($file, 'public://images');

        $node->field_image[$node->language][] = (array) $file;
      }
    }
  }

  node_save($node);

I also tried this:

if (isset($uploads)) {
    foreach ($uploads as $upload) {
        $upload->status = 1;  

        file_save($upload);

        $node->field_image[$node->language][] = (array) $upload;
      }
    }
  }

  node_save($node);

The second causes a duplicate key error in MySQL on the URI field. Both of these examples I saw in tutorials, but neither are working?

Answer

Betsen picture Betsen · Jun 1, 2012

i used your code to upload a file in the file field to a content("document" in my case) and it's worked. Just had to add a value for field_document_file 'display' in the code. here is the exact script i used:

<?php
// Bootstrap Drupal
define('DRUPAL_ROOT', getcwd());
require_once './includes/bootstrap.inc';
require_once './includes/file.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

// Construct the new node object.
$path = 'Documents/document1.doc';
$filetitle = 'test';
$filename = 'document1.doc';

$node = new StdClass();

$file_temp = file_get_contents($path);

//Saves a file to the specified destination and creates a database entry.
$file_temp = file_save_data($file_temp, 'public://' . $filename, FILE_EXISTS_RENAME);

$node->title = $filetitle;
$node->body[LANGUAGE_NONE][0]['value'] = "The body of test upload document.\n\nAdditional Information";
$node->uid = 1;
$node->status = 1;
$node->type = 'document';
$node->language = 'und';
$node->field_document_files = array(
'und' => array(
    0 => array(
        'fid' => $file_temp->fid,
        'filename' => $file_temp->filename,
        'filemime' => $file_temp->filemime,
        'uid' => 1,
        'uri' => $file_temp->uri,
        'status' => 1,
        'display' => 1
    )
)
);
$node->field_taxonomy = array('und' => array(
0 => array(
    'tid' => 76
)
));
node_save($node);
?>