13

Is there a way to load a file by URI in Drupal 8 or Drupal 9?

In Drupal 7 it is possible by the next example:

$uri = 'public://file.xyz';

// Take a look at: file.inc::file_load_multiple
$files = file_load_multiple(array(), array('uri' => $uri));
$file = reset($files); // If empty, $file will be false, otherwise will contain the required file

Taken from here https://www.drupal.org/forum/support/module-development-and-code-questions/2012-06-06/load-a-file-by-uri#comment-6493610

23

There is the loadByProperties method in the \Drupal\Core\Entity\EntityStorageInterface that allows to define required condition in searching the file entity by the given file URI:

/* @var \Drupal\file\FileInterface[] $files */
$files = \Drupal::entityTypeManager()
  ->getStorage('file')
  ->loadByProperties(['uri' => $uri]);
| improve this answer | |
  • To exactly match the code example in the original question, add $file = reset($files); again. – marcvangend Jul 3 at 13:52

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.