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://
?
Drupal Answers is a question and answer site for Drupal developers and administrators. It only takes a minute to sign up.
Sign up to join this communityI 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://
?
$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!
public://
. Ideally I would like to use a service.
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
.
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.
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" />
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())