Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Response::download() to show images in Laravel

So i figured out two possibility to store and show images in laravel 5. First way: to show images I have a route (e.g. loadFile/profil/{profilID}/main), which returns:

return Response::download($filepath)

My images are stored inside the storage folder, and therefore i can not access them via url, because this: www.domain.com/sotrage/files/... obviously does not work.

The other posibility would be to store the images inside the public folder and access them via their url.

My question: which of the two posibilitys i should use and what is best practice to store images in Laravel overall.

like image 294
Jodo Avatar asked Mar 27 '15 12:03

Jodo


2 Answers

Image Upload

$path = public_path('uploads/image/')
$file_name = time() . "_" . Input::file('image')->getClientOriginalName();
Input::file('image')->move($path, $file_name);

Download Image

$filepath = public_path('uploads/image/')."abc.jpg";
return Response::download($filepath);
like image 87
Jay Dhameliya Avatar answered Oct 31 '22 23:10

Jay Dhameliya


Jay's solution uses public_path(), this takes your code outside of the framework's guarantees. Make sure that you are doing so wittingly if you opt for his solution.

By using File:: on your storage, or low-level php primitives like is_file(), readfile(), or public_path(), your code will now break when you switch from a local storage to an external solution. The purpose of using Flysystem in the first place is to keep your code abstracted from this and allow easy switching between local storage, amazon s3, sftp or whatever.

Hence, if you've been using the Storage class thus far, you should want to bind yourself to it when you can. Your particular issue has a perfectly good workaround using just the Storage:: methods

The proper way of doing it

Storage::download() allows you to inject HTTP headers into the response. By default, it includes a sneaky 'Content-Disposition:attachment', this is why your browser doesn't "display" the picture, and prompts you instead.

You want to turn that into a 'Content-Disposition:inline'.

Here's how to overwrite it:

// Overwrite the annoying header
$headers = array(
    'Content-Disposition' => 'inline',
);

return Storage::download($storage_path, $filename, $headers);

Or you can use Storage::get()

But this one requires you to fetch the type.

$content = Storage::get($path);
return response($content)->header('Content-Type', $type);
like image 39
nargyriou Avatar answered Oct 31 '22 23:10

nargyriou