4

I can get the path to the public files directory by using Filesystem::realpath:

$path = $filesystem->realpath('public://');

But how can I get the URL of public://?

2

5 Answers 5

14
$my_path = file_create_url("public://"); 

Will definately work, however it's not coming from a service. Let me investigate more on this!

Okey I found it! This is how file_create_url works:

And this is the corresponding line specific to "public://" resolving (if you are sure you are trying to resolve a "public://..." uri):

  if ($wrapper = \Drupal::service('stream_wrapper_manager')->getViaUri($uri)) {
  return $wrapper->getExternalUrl();
}

Which means you will have to use StreamWrapperManager service, and after calling the getViaUri, you will able to get the external url. So this is service based solution!

3
  • 1
    I looked at Url::fromUri, but couldn't get it to work with public://. Ideally I would like to use a service.
    – Tim
    Jun 8, 2016 at 14:46
  • file_create_url works fine.
    – Tim
    Jun 8, 2016 at 14:48
  • Came back to this. stream_wrapper_manager works as intended!
    – Tim
    Oct 17, 2017 at 10:21
2

After Drupal 9.3.3, you can do this with the field_url_generator service.

$url = \Drupal::service('file_url_generator')->generate('public://basename.ext'); 

This returns a path to the file like /sites/default/files/basename.ext.

0

Another way to achieve it.

$wrapper = \Drupal::service('stream_wrapper_manager')->getViaScheme(file_default_scheme());
return $wrapper::baseUrl();

will return DOMAIN/sites/default/files for my case. For 'public', $wrapper belongs to class "PublicStream", you can check other methods inside.

I've added it because this works for me:

$my_path = file_create_url("public://");

But this not work:

if ($wrapper = \Drupal::service('stream_wrapper_manager')->getViaUri($uri)) {
  return $wrapper->getExternalUrl();
}

in my project, it returns "public://".

Maybe it's related to update of Drupal Core or some settings. Unfortunately, it's not easy to find the root cause. I hope this information will be helpful for somebody.

0

I was having -

public://2019-03/YxoEy6.png

and I got the image by -

<img class="item-logo" src="{{file_url(restricted_item.logo_name.logo )}}" alt="logo" />
0

Drupal 9 and 10

Use the FileUrlGenerator service:

$urlEntity = \Drupal::service('file_url_generator')->generate($file->getFileUri())
$url = $urlEntity->toString();

// or

$url = \Drupal::service('file_url_generator')->generateString($file->getFileUri())

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.