[SOLVED] How to Load a file Entity by URI in Drupal 9?

By | 03rd Feb 2022 | 1 min read

 

We can use loadByProperties method in the \Drupal\Core\Entity\EntityStorageInterface.it will help us to search the file entity by the given file URI:

/** @var \Drupal\file\FileInterface[] $files */
$files = \Drupal::entityTypeManager()
  ->getStorage('file')
  ->loadByProperties(['uri' => $uri]);
/** @var \Drupal\file\FileInterface|null $file */
$file = reset($files) ?: NULL;

In some other cases if you don't know the file URI   
We can use the below code to get the URI:

function _mymodule_get_file_data($file_url) {
  $file_name = Drupal::service('file_system')->basename($file_url);
  $target_file = Drupal::entityTypeManager()->getStorage('file')->loadByProperties(['filename' => $file_name]);
  $file_data = reset($target_file);
  if ($file_data) {
    return($file_data);
  }
  else {
    return FALSE;
  }
}
            
// Usage. 
//File URL              
$file_url = 'https://drupal.stackexchange.com/sites/default/files/2020-10/blog-images/stack.jpg';
$get_file_data = _mymodule_get_file_data($file_url);
// File ID.
$file_id = $get_file_data->get('fid')->value;            
// File URI.
$file_url = $get_file_data->get('uri')->value;
// Should print 'public://2020-10/blog-images/stack.jpg' or 'private://2020-10/blog-images/stack.jpg'.
        
// Uploader user ID.
$get_uploader_user_id = $get_file_data->get('uid')->value;

Reference

https://drupal.stackexchange.com/questions/262862/load-a-file-entity-by-uri