6

I have a file with an uri and I want to get its raw and relative path.

Uri: public://videos/Test Video.mp4 Path: /sites/default/files/videos/Test Video.mp4

I found already a way to do this:

$file_uri = $file->getFileUri();
// public://videos/Test Video.mp4

$absolute_url = file_create_url($file_uri);
// https://www.example.com/sites/default/files/videos/Test%20Video.mp4

$relative_url = file_url_transform_relative($absolute_url);
// /sites/default/files/videos/Test%20Video.mp4

$relative_raw_url = rawurldecode($relative_url);
// /sites/default/files/videos/Test Video.mp4

Is this the Drupal-way? Or is there a better solution for doing this?

3
  • the question seems to invite opinions here. Is there a certain concern or worry you have about using the File API functions here?
    – Shawn Conn
    Commented Mar 15, 2019 at 20:22
  • 1
    Hi @ShawnConn! Thanks for your comment. Well I hope it's not just a thing of opions. I want to ask for a better solution if there is a better solution. I have a $file and I want to have the relative path. Do I really have to call 4 different File API functions?
    – btemperli
    Commented Mar 16, 2019 at 14:10
  • I think I understand the concern. See below.
    – Shawn Conn
    Commented Mar 16, 2019 at 22:19

3 Answers 3

10

I had to do this recently and found this solution using Drupal 9.1.

$file = File::load($fid);

$relative_file_url = $file->createFileUrl(TRUE);
$absolute_file_url = $file->createFileUrl(FALSE);

I found the createFileUrl() function in web/core/modules/file/src/Entity/File.php. Maybe this would be considered "the way?"

3

The "Drupal way" is always a fuzzy term because there's usually more than one answer that works.

Anyway, if you're looking for something less verbose, it would help to look at the File object and it's url() method. That saves you some steps and might save you some work down the road if the old D7 file module API functions get slated for depreciation (like file_load has).

Lastly, it always helps to use native PHP functions when you can since they make things more portable. To wit, parse_url() allows you to slice/dice URLs to the components you want.

Putting it all together, rawurldecode(parse_url($file->url(), PHP_URL_PATH)) pulls all your function call together for one result.

1
2
$relative_file_url =  \Drupal::service('file_url_generator')
    ->generateAbsoluteString($uri);

Your Answer

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

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