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

Jod*_*odo 6 php image file laravel-5

所以我想出了两种在laravel 5. 第一种方式:显示图像我有一个路线(例如loadFile/profil/{profilID}/main),它返回:

return Response::download($filepath)
Run Code Online (Sandbox Code Playgroud)

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

另一种可能性是将图像存储在公共文件夹中并通过它们的 url 访问它们。

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

小智 6

图片上传

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

下载图片

$filepath = public_path('uploads/image/')."abc.jpg";
return Response::download($filepath);
Run Code Online (Sandbox Code Playgroud)


nar*_*iou 5

Jay 的解决方案使用public_path(),这会使您的代码超出框架的保证。如果您选择他的解决方案,请确保您是有意这样做的。

通过在您的存储上使用、、 或 等File::低级 php 原语,当您从本地存储切换到外部解决方案时,您的代码现在将会中断。使用 Flysystem 的首要目的是让您的代码从中抽象出来,并允许在本地存储、亚马逊 s3、sftp 或其他存储之间轻松切换。is_file()readfile()public_path()

因此,如果您到目前为止一直在使用 Storage 类,那么您应该尽可能将自己绑定到它。您的特定问题有一个非常好的解决方法,仅使用 Storage:: 方法

正确的做法

Storage::download()允许您将 HTTP 标头注入到响应中。默认情况下,它包含一个偷偷摸摸的“内容处置:附件”,这就是为什么您的浏览器不“显示”图片,而是提示您。

您想将其变成“Content-Disposition:inline”。

覆盖它的方法如下:

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

return Storage::download($storage_path, $filename, $headers);
Run Code Online (Sandbox Code Playgroud)

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

但这需要您获取类型。

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