在Drupal 7中以编程方式将图像文件附加到节点上

是否有可能以编程方式将图像添加到节点?

这是一个使用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; ` 

更简单的方法:

 $filename = 'image.txt'; $image = file_get_contents('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)); 

这对我来说是有效的:

 $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 ) ) ); 

这里有一个额外的一点让我绊倒了一会儿:这将把图像附加到节点,如果你添加图像,那么你没事。 但是,如果你正在更新一个图像,并且你关心在一个页面上显示它,那么在调用node_save()之前需要一个额外的步骤:

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

这将重新生成所有图像的样式。

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

我尝试了一个多语言网站。 它失败了,但可怕的是。 我不得不指定有问题的语言。 简单地说,这个工作,而不是:

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

没有它,附加文件可以在“查看”屏幕中查看,但不能在“编辑”屏幕中查看。

是的,在保存时将它作为$ node对象的一部分。 使用node_save()保存它。

这适用于我:

 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('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); 

只要在这里粘贴我的解决scheme,我需要创build一个新的节点,并以编程方式上传图片。

 $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);