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.
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.
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();
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();