1

As part of some other functionality I am generating an image in temp folder and But unforunately I'm not able get the web url of image.

$path = \Drupal::service('file_system')->realpath(file_default_scheme() . "://");
$image_path = $path . rand() . '.png';
echo $image_path;

I am getting following as path

C:\wamp\www\www_d8test1_com\sites\default\files30605.png

How can I add slash before image name and get actual weburl of image like below?

http://www.d8test1.com/sites/default/files/30605.png

2 Answers 2

0

You can check out the file_create_url() function that creates a URL for your file.

So, based on the code in your question, it would look like:

// Generate or get the image uri.
$image_uri = file_default_scheme() . "://";
// Create the url from the uri.
$image_path = file_create_url($image_uri);
0

Try the following explained here:

$handle = fopen('<path to local file>', 'r');
$file = file_save_data($handle, file_default_scheme() . '<filename>');
fclose($handle);

and then try:

file_create_url(file_default_scheme() . '<filename>');
3
  • Drupal can deliver other files too, but this is exactly what the code in OP needs, default_scheme() is public:// by default, no reason to call realpath() and then file_create_url() willl work nicely, no idea why this was downvoted
    – Berdir
    Commented May 31, 2017 at 23:58
  • I updated my answer.
    – schneidolf
    Commented Jun 1, 2017 at 6:00
  • @Berdir maybe you can provide an answer or edit my answer how to deliver files outside of a file scheme. Is it possible to deliver files from scheme temporary:// ?
    – schneidolf
    Commented Jun 3, 2017 at 9:19

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.