The best方法是创建一个符号链接就像@SlateEntropy 很好地指出的那样下面的答案 https://stackoverflow.com/a/30192351/351330。为了解决这个问题,从 5.3 版本开始,Laravel包括一个命令 https://laravel.com/docs/5.3/filesystem#configuration这使得这变得非常容易做到:
php artisan storage:link
这会创建一个符号链接public/storage
to storage/app/public
对于你来说,这就是全部。现在任何文件/storage/app/public
可以通过以下链接访问:
http://somedomain.com/storage/image.jpg
如果出于任何原因,您无法创建符号链接(也许您位于共享主机等),或者您想保护某些访问控制逻辑背后的某些文件,则可以选择使用特殊的路径来读取和服务于形象。例如,像这样的简单关闭路线:
Route::get('storage/{filename}', function ($filename)
{
$path = storage_path('public/' . $filename);
if (!File::exists($path)) {
abort(404);
}
$file = File::get($path);
$type = File::mimeType($path);
$response = Response::make($file, 200);
$response->header("Content-Type", $type);
return $response;
});
您现在可以像有符号链接一样访问您的文件:
http://somedomain.com/storage/image.jpg
如果您正在使用干预图像库 http://image.intervention.io/api/response你可以使用它内置的response
使事情更简洁的方法:
Route::get('storage/{filename}', function ($filename)
{
return Image::make(storage_path('public/' . $filename))->response();
});
WARNING
请记住,通过手动服务您遇到的文件绩效惩罚,因为您要经历整个 Laravel 请求生命周期才能读取和发送文件内容,即相当慢而不是让 HTTP 服务器处理它。