3

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://?

8
$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!

  • 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 '16 at 14:46
  • file_create_url works fine. – Tim Jun 8 '16 at 14:48
  • Came back to this. stream_wrapper_manager works as intended! – Tim Oct 17 '17 at 10:21
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" />

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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