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
Thanks.
It works for me.
Add new comment