0

I am in middle of coding creating nodes programatically. Here i have one problem. I need to programmatically attach image to the content type from local system folder. I mean my image path example 'c://xxxxx/xxxx/images/img.jpg'.

Thanks in advance for your advice.

Hi i used this code and work fine in the localhost. But it's failed when i work on the server.

$filepath = drupal_realpath('misc/druplicon.png');
// Create managed File object and associate with Image field.
$file = (object) array(
 'uid' => 1,
 'uri' => $filepath,
 'filemime' => file_get_mimetype($filepath),
 'status' => 1,
);

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

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

Reference link : attaching-files-to-nodes-programmatically-in-drupal-7

I didn't get the solution yet. Can any one have the experience?

  • Did you check your file permissions to make sure you can copy into the folder? admin/config/media/file-system – iLLin Mar 19 '13 at 13:41
  • 1
    Also check your logs to see if there is any error messages in there. admin/reports/dblog – iLLin Mar 19 '13 at 13:42
1

You can just use file_copy or file_move.

Here is an example: https://stackoverflow.com/questions/5129559/attaching-files-to-nodes-programmatically-in-drupal-7

1

I usually use a code like this:

$filepath = 'TheFilePath';
$file = new stdClass();
$file->filename = basename($filepath);
$file->filepath = $filepath;
$file->filemime = file_get_mimetype($filepath);
$file->filesize = filesize($filepath);
$file->uid = 1;
$file->status = FILE_STATUS_PERMANENT;
$file->uri = $filepath;
$file->display = 1;
$file->description = '';
$file = file_copy($file, 'public://news-images', FILE_EXISTS_REPLACE);

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

And it works...so I hope it helps for you too!

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.