Laravel Response::download() 显示 Laravel 中的图像

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

所以我想出了两种在 laravel 5 中存储和显示图像的可能性。第一种方式:显示图像我有一条路线(例如 loadFile/profil/{profilID}/main),其中 returns:

return Response::download($filepath)

我的图像存储在存储文件夹中,因此我无法通过 url 访问它们,因为这:www.domain.com/sotrage/files/... 显然不起作用。

另一种可能性是将图像存储在 public 文件夹中并通过 url.

访问它们

我的问题:我应该使用两种可能性中的哪一种,以及将图像总体存储在 Laravel 中的最佳做法是什么。

/**
 * .
 * ├── 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.

图片上传

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

下载图片

$filepath = public_path('uploads/image/')."abc.jpg";
return Response::download($filepath);

您应该在您的存储上使用File::anything()。或 is_file()readfile()public_path() 或类似的任何内容。因为如果您将数据切换到远程主机,这将会中断,并且首先会破坏使用 Flysystem 的目的。

Laravel 中存储 class 的一个要点是能够在本地存储、amazon s3、sftp 或其他任何存储之间轻松切换。

正确的做法

Storage::download() 允许您将 HTTP headers 注入到响应中。默认情况下,它包含一个偷偷摸摸的 'Content-Disposition:attachment',这就是为什么您的浏览器不 "display" 图片,而是提示您的原因。

你想把它变成 'Content-Disposition:inline'。

覆盖方法如下:

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

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

或者你可以使用Storage::get()

但是这个需要你获取类型。

$content = Storage::get($path);
return response($content)->header('Content-Type', $type);