Scenario 1: If the file resides on the other server/website. Try the below code, use \Drupal\node\Entity\Node; /** Create file object from remote server/website URL. */ $data = file_get_contents('https://www.example.com/sites/default/files/logo.png'); $file = file_save_data($data, 'public://logo.png', FILE_EXISTS_REPLACE); // Create node object with attached file. $node = Node::create([ 'type' => 'article', 'title' => 'Sample test', 'field_image' => [ 'target_id' => $file->id(), ], ]); $node->save(); Refer " file_save_data " API for more options/overide functions Scenario 2: If the file resides on the same server/website. Try the below code, use \Drupal\node\Entity\Node; use \Drupal\file\Entity\File; // Create file object from a locally copied file. $uri = file_unmanaged_copy('public://source.jpg', 'public://destination.jpg', ...
Comments