Drupal - How can I get the file id if I use the file_save_data function?

Try

$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(),
  ],
]);
$node->save();

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,
]);
$file->save();

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

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',
]);
$node->field_image->generateSampleItems();
$node->save();

Tags:

Entities

Files

8