Adding a file to a node programmatically

Submitted by Jochus on Fri, 29/10/2010 - 00:57 | Posted in: Drupal

Ever wondered how you add a file to node in code? It's really easy :-) ... Please note that the file was already on the server (on a temporary location)

/**
 * @param node the node to which you want to add the file
 * @param file the path to the file: e.g.: /tmp/image.jpg
 * @return TRUE if success, FALSE if not
 */
function store_file($node, $file) {
    if (!isset($file) || !file_exists($file)) {
        drupal_set_message('File does not exists');
        return FALSE;
    }
 
    $details = stat($file);
    $filesize = $details['size'];
    $dest = file_directory_path();
    if(!file_copy($file,$dest)) {
        drupal_set_message("Failed to move file: $file");
        return FALSE;
    } else {
        $name = basename($file);
    }
 
    // build the file object
    $file_obj = array();
    $file_obj['filename'] = $name;
    $file_obj['filepath'] = $file;
    $file_obj['filemime'] =  file_get_mimetype($name);
    $file_obj['filesize'] = $filesize;
    $file_obj['status'] = FILE_STATUS_TEMPORARY;
    $file_obj['timestamp'] = time();
    $file_obj['list'] = 1;
    $file_obj['new'] = TRUE;
    $file_obj['data']['alt'] = 'foo';
    $file_obj['data']['title'] = 'bar';
    $file_obj['uid'] = '1'; // 1 = admin, but you can do here whatever you want ...
 
    // save file to files table, fid will be set
    drupal_write_record('files', $file_obj);
 
    // change file status to permanent
    file_set_status($file_obj, 1);
 
    // attach the file object to your node
    $node->field_main_picture[0] = $file_obj; // property can be different 
    return TRUE;
}

Comments

Submitted by BN pandey (not verified) on Wed, 11/05/2016 - 15:51
 

Thanks.
It works for me.

Add new comment

The content of this field is kept private and will not be shown publicly.

Full HTML

  • Lines and paragraphs break automatically.
  • You can caption images (data-caption="Text"), but also videos, blockquotes, and so on.
  • Web page addresses and email addresses turn into links automatically.
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <bash>, <cpp>, <css>, <html5>, <java>, <javascript>, <php>, <sql>, <xml>. The supported tag styles are: <foo>, [foo].
CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.