I will be adding new media files in D8 programmatically, how do I determine what the fid should be for each one? also how do i put the actual file contents into the media type?
this is my code

  $file = file_get_contents($fullpath."/".$file_name); // string
 $filesaved = file_save_data($file, 'public://'.$file_directory_name."/".$file_info['file_name')',FILE_EXISTS_REPLACE);
  $fid = ???; 
  $static_media = Media::create([
      'bundle' => 'document',
      'uid' => '1',
      'langcode' => Language::LANGCODE_DEFAULT,
      'status' => Media::PUBLISHED,
      'your_image_field_name_here' => [
        'target_id' => $fid,
        'alt' => t('foo'),
        'title' => t('bar'),
  • The function file_save_data() returns a file entity. So i suppose you need $filesaved->fid->value.
    – Andrew Nim
    Mar 16 '17 at 22:26


$filesaved = file_save_data($file, 'public://'.$file_directory_name."/".$file_info['file_name']), 'FILE_EXISTS_REPLACE');
$fid = $filesaved->id; 

file->id is the id if file that you can use it as entity reference target_id (I mean file field).

and a good example how save and attach file to Node

use \Drupal\node\Entity\Node;

// Create file object from remote URL.
$data = file_get_contents('https://www.drupal.org/files/druplicon.small_.png');
$file = file_save_data($data, 'public://druplicon.png', FILE_EXISTS_REPLACE);

// Create node object with attached file.
$node = Node::create([
  'type'        => 'article',
  'title'       => 'Druplicon test',
  'field_image' => [
    'target_id' => $file->id(),

What if the file is already present in your local file system and you want to attach it to an existing node? Here's an example for that too:

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', FILE_EXISTS_REPLACE);
$file = File::Create([
  'uri' => $uri,

// Load existing node and attach file.
$node = Node::load(1);
  'target_id' => $file->id(),

And lastly, what if you want to stick a placeholder file to a node? Thanks to Drupal 8, this is too easy:

use \Drupal\node\Entity\Node;

$node = Node::create([
  'type'  => 'article',
  'title' => 'Generated image test',
  • 2
    Shouldn't this be $file->id()?
    – user1359
    Feb 6 '18 at 20:18

file_save_data returns a file object on a successful save. That object must be an instance of FileInterface.

As such, then you can just do:

$fid = $filesaved->id();


The function file_save_data() returns a file entity. So i suppose you need $filesaved->fid->value. And $filesaved->id() returns the same result.

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.