I am trying to update a node and programmatically upload a file.

$nid = 45343;
$node = node_load($nid);

$image_url = 'http://test.com/misc/druplicon.png';
$file = system_retrieve_file($image_url, file_default_scheme().'://products_images/'.basename($image_url), TRUE);

// We save the file to the root of the files directory.
// $file = file_copy($file, 'public://');

$node->field_custom_file[LANGUAGE_NONE][0] = (array)$file;

Somehow, it's not working at all. Do I need to add more functions to it?

  • It looks right, but where are you running that code from? – Clive Jan 12 '16 at 18:32
  • I am testing it in running it in the page.tpl.php – Boby Jan 13 '16 at 0:24

The following code works for me.

$image_url = 'http://test.com/misc/druplicon.png';    
$file_info = system_retrieve_file($image_url, 'public://documents/', TRUE);

if ($file_info->fid) {
  $node->field_custom_file['und'][0]['fid'] = $file_info->fid;

$node_ready = node_submit($node);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.