$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?
Drupal Answers is a question and answer site for Drupal developers and administrators. It only takes a minute to sign up.
Sign up to join this community$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?
// 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());
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()
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());
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.
to get the file intity
$file = \Drupal\file\Entity\File::load($fid);
to get the file url
$url = $file->url();