How can i get the absolute path for a file based on the fid? Sorry if this is a repeat, I did a search but was unable to find the answer.
5 Answers
Drupal 7
This is a two part process, using file_load() and file_create_url()
First, you need to turn the $fid into a Drupal URI:
$file = file_load($fid); $uri = $file->uri; Now, you can turn this into a URL
$url = file_create_url($uri); file_create_url() always creates an absolute URL, either using the global $base_path that you have defined, or using the one that Drupal guessed during bootstrap.
- 1I am surprised you have to load the file just to get the path, seems like a waste of resources.Russ– Russ2014-02-28 03:55:45 +00:00Commented Feb 28, 2014 at 3:55
- 2@Russ It's loading the file object, not the file itself. You could also do a db_query to get the uri, but I try to use the API as much as possible.2014-02-28 04:05:33 +00:00Commented Feb 28, 2014 at 4:05
- Thanks, I figured that, just thought there would be a clean function that could return it in one step. Maybe something to consider in drupal 8.Russ– Russ2014-02-28 13:21:03 +00:00Commented Feb 28, 2014 at 13:21
- 2In your example you have 'field_load($fid)', it should be 'file_load($fid)'.Steve Mulvihill– Steve Mulvihill2018-09-08 20:47:28 +00:00Commented Sep 8, 2018 at 20:47
- 2@SteveMulvihill Wow, nice catch. Four+ years and 33 votes, and nobody noticed that.2018-09-08 21:42:30 +00:00Commented Sep 8, 2018 at 21:42
Drupal 8
$file = \Drupal\file\Entity\File::load($file_id); $uri = $file->getFileUri(); $url = \Drupal\Core\Url::fromUri(file_create_url($uri))->toString(); - It works also only by calling file_create_url($uri); which is already returning the URL as a string.user3554770– user35547702021-09-15 08:14:20 +00:00Commented Sep 15, 2021 at 8:14
In Drupal 7 you can also use MYSQL query, if you don't want to load all the fields of the file
$fid = 1; //your file ID $uri = db_select('file_managed', 'f') ->condition('f.fid', $fid, '=') ->fields('f', array('uri')) ->execute()->fetchField(); echo file_create_url($uri); Drupal 9
All previous answers are now deprecated using Drupal 9. There is a perfect list of the up-to-date alternatives : https://www.drupal.org/node/2940031
An example step by step :
$file = File::load(15); $uri = $file->getFileUri(); $url = \Drupal::service('file_url_generator')->generate($uri); // Your url as a string $string = $url ->toString(); - 1\Drupal::service('file_url_generator')->generateAbsoluteString($uri);macherif– macherif2023-09-29 12:43:58 +00:00Commented Sep 29, 2023 at 12:43
These are both working for me in Drupal 8:
// top of file use Drupal\file\Entity\File; use Drupal\Core\Url; // load the file object from some file id $file_object = File::load(123); // way 1 $file_uri = $file_object->uri->value; $file_url = file_create_url($file_uri); // way 2 $file_uri = $file_object->getFileUri(); $file_url = Url::fromUri(file_create_url($file_uri))->toString();