Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drupal 6 Programmatically adding an image to a FileField

How do I programmatically add an image to a file field? I have an url/filepath of an image that I wish to upload. I have tried the following:

$newNode->field_profile_image[0]['value'] = 'http://www.mysite.com/default.gif';

But it does not seem to work.

I have also tried:

$newNode->field_profile_image[0]['value'] = 'sites/default/files/default.gif';

The file does not need to be external to the webiste. I am happy to have it anywhere on the site in question.

like image 931
Sally Avatar asked Dec 14 '25 09:12

Sally


1 Answers

You're probably going to have to use hook_nodeapi to set this correctly. You're going to want to modify it under the "Insert" operation. Make sure that you resave the node after you've added the required fields.

Drupal wants to map the image to an entry in the file table, so simply setting the URL will not work. First off, if it's a remote file, you can use the function listed in the Brightcove module on line 176, brightcove_remote_image, to grab the image and move it into your local directory.

Once the remote image is moved into place, you need to save it into the files table and then properly configure the node's property. I've done it in this method:

////// in NodeAPI /////
    case "insert":
        $node->field_image[0] = _mymod_create_filearray($image_url);
        node_save($node);

This writes the files record, and then returns a properly formatted image array.

///// mymod_create_filearray /////
function _mymod_create_filearray($remote_url){
  if ($file_temp = brightcove_remote_image($remote_url)) {
    $file = new stdClass();
    $file->filename = basename($file_temp);
    $file->filepath = $file_temp;
    $file->filemime = file_get_mimetype($file_temp);
    $file->filesize = filesize($file_temp);

    $file->uid = $uid;
    $file->status = FILE_STATUS_PERMANENT;
    $file->timestamp = time();
    drupal_write_record('files', $file);

    $file = array(
     'fid' => $file->fid,
      'title' => basename($file->filename),
      'filename' => $file->filename,
      'filepath' => $file->filepath,
      'filesize' => $file->filesize,
      'mimetype' => $mime,
      'description' => basename($file->filename),
      'list' => 1,
    );
    return $file;
  }
  else {
    return array();
  }
}

And that should do it. Let me know if you have any questions.

like image 73
jacobangel Avatar answered Dec 16 '25 21:12

jacobangel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!