Attaching image files to nodes programmatically in

2019-01-16 05:33发布

Is it possible to add an image to a node programmatically?

8条回答
趁早两清
2楼-- · 2019-01-16 06:00

An easier way:

$filename = 'image.txt';
$image = file_get_contents('http://www.ibiblio.org/wm/paint/auth/gogh/gogh.white-house.jpg');
$file = file_save_data($image, 'public://' . $filename, FILE_EXISTS_RENAME);
$node->field_image = array(LANGUAGE_NONE => array('0' => (array)$file));
查看更多
Anthone
3楼-- · 2019-01-16 06:06

This is what worked for me:

$file_temp = file_get_contents('public://someimage.jpg');

// Saves a file to the specified destination and creates a database entry.
$file_temp = file_save_data($file_temp, 'public://' . 'someimage.jpg', FILE_EXISTS_RENAME);

$node->field_page_image = array(
  'und' => array(
    0 => array(
      'fid' => $file_temp->fid,
      'filename' => $file_temp->filename,
      'filemime' => $file_temp->filemime,
      'uid' => 1,
      'uri' => $file_temp->uri,
      'status' => 1,
      'display' => 1
    )
  )
);
查看更多
做自己的国王
4楼-- · 2019-01-16 06:06

Just going to paste my solution here as well, I needed to create a new node, and upload an image programmatically.

$filepath = variable_get('file_public_path') . '/xmas_banner.jpg';
$file_temp = file_get_contents($filepath);
$file_temp = file_save_data($file_temp, file_default_scheme() . '://' .'xmas_banner_nl.jpg', FILE_EXISTS_RENAME);

$node = new stdClass();
$node->type = 'carousel'; // custom content type
$node->title = 'XMAS NL';
$node->field_banner_image[LANGUAGE_NONE][0] = (array) $file_temp;
$node->uid = 1;
$node->status = 0;
$node->active = 0;
$node->promote = 0;
node_save($node);
查看更多
狗以群分
5楼-- · 2019-01-16 06:10

Here's one extra bit that tripped me up for a while: this will attach the image to the node, and if you're adding the image then you're okay. However, if you're updating an image, and you care about displaying it on a page, then one extra step is needed before calling node_save():

image_path_flush($node->field_image['und'][0]['uri']);

This will regenerate all of that image's styles.

查看更多
再贱就再见
6楼-- · 2019-01-16 06:10

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

I tried this with a multilingual site. It failed fairly... but horribly. I had to specify the language in question. Simply put, this worked instead:

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

Without it, the attached file was viewable in the 'view' screen but not in the 'edit' screen.

查看更多
来,给爷笑一个
7楼-- · 2019-01-16 06:12

Yes, make it part of the $node object when you save it. Save it using node_save().

查看更多
登录 后发表回答