【问题标题】:How to show image from storage folder in Laravel 5.3?如何在 Laravel 5.3 中显示存储文件夹中的图像?
【发布时间】:2016-11-28 18:26:38
【问题描述】:

我在 Laravel 5.3 项目中有一个位于 storage 的文件夹,其中包含图像文件。

如何显示该文件夹中的图像?

我有所有的名字

Storage::allFiles('images');

由于文件夹权限,我无法以通常的方式访问它们,并且我不想更改它们。 我也不想把文件放在 Public 目录中。

有什么建议吗? 提前致谢。

【问题讨论】:

    标签: php laravel-5


    【解决方案1】:

    您可以编写一个控制器函数来返回图像...类似于:

    public function image($file){
        $image = storage_path('images/' . $file);
    
        if(!File::exists( $image ))
            App::abort(404);
    
        // using Intervention Image package
        return Image::make($image)->response('jpg');
    
        // using Laravel file response
        $headers = ['Content-Type' => 'image/jpeg'];
        return response()->file($image, $headers);
    }
    

    当然,这是非常简单的...您可以对其进行修饰以按需调整大小、检查 mime 类型并基于此返回正确的响应类型等。

    【讨论】:

    • 对于每张图片我都应该调用这个函数吗?
    • 是的,你已经设置了一个路由:Route::get('/image/{file}', 'ImageController@image'); 所以当你向/image 发出 GET 请求时,它会通过这个函数提供服务。
    • 顺便说一句,对于与此类似的用例,我从干预图像包中获得了非常好的结果。 image.intervention.io
    • 哦,哎呀!我想我的示例确实使用了干预图像包...您可以轻松地重写它以提供图像响应...return response()->file($image, $headers);
    • 您将添加一个路由(就像我在第一条评论中提到的那样)以通过 URL 访问图像...在您的 img src 属性中使用该路由。
    猜你喜欢
    • 2017-09-03
    • 2020-12-19
    • 2017-05-30
    • 2017-06-18
    • 2021-02-07
    • 2019-03-11
    • 1970-01-01
    • 1970-01-01
    • 2018-10-27
    相关资源
    最近更新 更多