0

I have a laravel 5.7 project where I am trying to render an image to the browser.

If I just take the content of the file, it works as below:

$contents = Storage::disk($file->disk)->get($file->path);

$new = 'data:'.$file->mimetype.';base64,' . base64_encode($contents);
echo '<img src="'. $new .'">';

By using the above code I can see the image as the way we see in a html file with img tag. But I don't want this!

I want to render the image only as way we see an image in the browser! So I am trying to attach the header type as below:

$contents = Storage::disk($file->disk)->get($file->path);

return response($contents)
        ->header('Content-Type', $file->mimetype)
        ->header('Content-Disposition', 'inline;');

The above code does not work and I get error as "The image [url] can not be displayed, because it contains error";

I have no clue what I am mising here!

I don't want to keep those image files in public area and PDF file works fine with same approch.

Abdul
  • 472
  • 1
  • 5
  • 13
  • Possible duplicate of [Laravel 5 - How to access image uploaded in storage within View?](https://stackoverflow.com/questions/30191330/laravel-5-how-to-access-image-uploaded-in-storage-within-view) – César Escudero Jul 15 '19 at 15:58
  • did you run php artisan storage:link already? – Ghiffari Assamar Jul 15 '19 at 18:25
  • @GhiffariAssamar, I did storage:link already but in my senario it's not required. Because I don't want them to be available to public! – Abdul Jul 16 '19 at 15:04

1 Answers1

0

If you are using a local disk, you can return a file like this:

return response()->file('/your/file/path/image.png');

EDIT

In response to your comment...

I mentioned local disk, not public disk. They are two different things. You can still use this with protected files.

public function show(File $file)
{
    // allow or deny according to File Policy
    // you would need to create a policy if you don't already have one
    $this->authorize('view', $file);

    // serve the local file
    return response()->file(storage_path($file->path));
}
matticustard
  • 4,850
  • 1
  • 13
  • 18
  • Hi, This approch is not okay for me as my images are not in public directory and I don't want to keep them in public directory either! All the file is hashed and kept them in out side of public area. When trying to access then check the access rights; if allowed then get the file contents and serve in the browser. In my senario the file could be pdf or image. PDF file serve fine but doesn't work images! Images also work if I take the contents and conver them in to base_64 – Abdul Jul 16 '19 at 14:57
  • This approach has nothing to do with the public directory. It serves files from any system path. – matticustard Jul 16 '19 at 15:20
  • I added additional edits to illustrate how this method would be used with protected files. – matticustard Jul 16 '19 at 15:32