简体   繁体   中英

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 (eg 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.

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);

You should not use File::anything() on your storage. Or is_file() , readfile() , or public_path() or anything like that. Because this will break if you switch your data to a remote host and defeats the purpose of using Flysystem in the first place.

One of the major point of the Storage class in Laravel is to be able to switch easily between local storage, amazon s3, sftp or whatever.

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);
/**
 * .
 * ├── public
 * │   ├── myimage.jpg
 * 
 * example.com/myimage.jpg
 */

The storage directory is used as temporary file store for various Laravel services such as sessions, cache, compiled view templates. This directory must be writable by the web server. This directory is maintained by Laravel and you need not tinker with it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM