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

jan*_*mon 42 drupal drupal-7

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

Dan*_*ner 52

下面是一个示例代码,您可以使用它与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;
`
Run Code Online (Sandbox Code Playgroud)

  • +1.无论出于何种原因,我还必须在$ file数组中添加`'display'=> 1`,否则我遇到了一个约束违规,即field_doc_file_display为NULL.这是针对文件而不是图像,这可能是差异. (4认同)

小智 31

更简单的方法:

$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));
Run Code Online (Sandbox Code Playgroud)


Ran*_*ell 7

这对我有用:

$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
    )
  )
);
Run Code Online (Sandbox Code Playgroud)