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-&gt;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'        =&gt; 'article',
  'title'       =&gt; 'Druplicon test',
  'field_image' =&gt; [
    'target_id' =&gt; $file-&gt;id(),
  ],
]);
$node-&gt;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' =&gt; $uri,
]);
$file-&gt;save();

// Load existing node and attach file.
$node = Node::load(1);
$node-&gt;field_image-&gt;setValue([
  'target_id' =&gt; $file-&gt;id(),
]);
$node-&gt;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'  =&gt; 'article',
  'title' =&gt; 'Generated image test',
]);
$node-&gt;field_image-&gt;generateSampleItems();
$node-&gt;save();