14

$node->field_file gives me a FileFieldItemList while the first entry seems to be a FileItem.

$node->field_file->getValue() gives me an integer (I guess the file id). How can I actually get the downloadable file uri from that?

5 Answers 5

25
// Load the file.
$file = \Drupal\file\Entity\File::load($fid);
// Get the URL.
$url = \Drupal::service('file_url_generator')
  ->generateAbsoluteString($file->getFileUri());

Before Drupal 10, there was a different way of doing it using file_create_url().

$url = file_create_url($file->getFileUri());
2
  • 3
    You can use File::url() to make this shorter: $imageSRC = $file->url();
    – keithm
    Aug 25, 2016 at 19:14
  • 3
    File:url() is deprecated as of 8.7.x. See: drupal.org/node/3019830
    – neuquen
    Feb 7, 2020 at 19:25
13

As of 9.3.0 file_create_url is deprecated and it will be removed from 10.0.0 version. The new way to do it:

$file_uri = $node->field_file->entity->getFileUri();
\Drupal::service('file_url_generator')->generateString($file_uri);

This service has the following functions:
generate() generateString() generateAbsoluteString() transformRelative()

2
  • 3
    $file->createFileUrl() seems simplier and has the same result. It's using your given service but with the relative option - source : 'File entities returning the URL to the physical file in File::url() is deprecated, use $file->createFileUrl() instead. See drupal.org/node/3019830' and File.php
    – Pauleau
    Mar 10, 2022 at 12:24
  • Yes, now you mention it... I would not even look under the 'create' term for such function... Mar 11, 2022 at 14:03
7

It is also possible to do one-liner with magic method:

$node->field_file->entity->getFileUri();

Or to render as string

Option 1: $node->field_file->entity->url();

Option 2: file_create_url($node->field_file->entity->getFileUri());

5

For Drupal 9.3.0+ users, as mentionned :

  • File:url() is deprecated as of 8.7.x.
  • file_create_url() is deprecated in drupal:9.3.0 and is removed from drupal:10.0.0

$file->createFileUrl() looks to be the new simplest solution.

It uses the 'file_url_generator' service mentionned by golddragon007.

You'll find details in the File.php core's file.

-1
to get the file intity

$file = \Drupal\file\Entity\File::load($fid);

to get the file url

$url = $file->url();
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.