5

I am trying to add an image to the article content type in Drupal 7, When I create a simple note i.e. article it works , but when I try to add the image to the article it gives an error

The specified file E:\WS_IntPOC_Test4\sites\all\modules\my_module\errorwinmobilesdk.jpg could not be copied, because the destination is invalid. More information is available in the system log

In log I can see the message as

File E:\WS_IntPOC_Test4\sites\all\modules\my_module\errorwinmobilesdk.jpg could not be copied, because the destination is invalid. This is often caused by improper use of file_copy() or a missing stream wrapper.

I have checked the wrapper public and private is there. As if I created the Article from GUI. It is created with image loaded in public folder. Please help

$body_text = 'node body text';

  $node = new stdClass();
  $node->type = 'article';
  node_object_prepare($node);

  $node->title    = 'Node Created Programmatically on ' . date('c');
  $node->language = LANGUAGE_NONE;

  $node->body[$node->language][0]['value']   = $body_text;
  $node->body[$node->language][0]['summary'] = text_summary($body_text);
  $node->body[$node->language][0]['format']  = 'filtered_html';



// Some file on our system

$path ='E:\WS_IntPOCTest4\sites\all\modules\my_module\errorwinmobilesdk.jpg' ;
$file = (object) array(
          'uid' => 1,
          'uri' => $path,
          'filemime' => file_get_mimetype($path),
          'status' => 1,
 ); 

//$file = file_copy($file, 'public://'); // Save the file to the root of the files 
$file = file_copy($file);
$node->field_image[LANGUAGE_NONE][0] = (array)$file; 
//associate the file object with the image field:
node_save($node);
1

You can try this code:

//$filepath = drupal_realpath('misc/image.jpeg');
 [**UPDATED ANSWER**:]
 $filepath =  $_SERVER['DOCUMENT_ROOT'].base_path() .drupal_get_path('module','payment_details').'/MDSO_20.jpg';


$file = (object) array(
       'uid' => 1,
       'uri' => $filepath,
       'filemime' => file_get_mimetype($filepath),
       'status' => 1,
  );
  $file = file_copy($file, 'public://');
  $node->field_image[LANGUAGE_NONE][0] = (array)$file;
  node_save($node);

Hope this works for you :)

For me it created a node as you below :)

enter image description here

0

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.