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:15

Here is an example code using which you can use with node_save

$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;
`
查看更多
兄弟一词,经得起流年.
3楼-- · 2019-01-16 06:17

This works for me:

define('DRUPAL_ROOT', $_SERVER['DOCUMENT_ROOT']);
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

$node = node_load(99);
$filename = 'image.txt';
chdir(DRUPAL_ROOT);
$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_imagen_producto = array(LANGUAGE_NONE => array('0' => (array)$file));
node_save($node);
查看更多
登录 后发表回答