从资源文件夹获取图像-Laravel

时间:2020-03-10 07:31:47

标签: laravel laravel-7

我可以从资源文件夹而不是公用文件夹中获取并显示图像吗?如果是,我该怎么办?

5 个答案:

答案 0 :(得分:4)

resources文件夹不应用于store images 那不是公共的静态资产(例如图像,js,css等)应该存在的地方。

将它们放在public/文件夹中

可以这么说,resources/assets/目录用于存储pre-processed资产。

例如,如果您有3个不同的CSS文件但要合并它们 合并成一个文件并在浏览器中呈现该新文件(以增加 页面加载速度)。在这种情况下,将放置3个CSS文件 在资源/资产/内部。

这些文件可以是processed,新的合并文件将进入公共目录。

参考:

https://laracasts.com/discuss/channels/laravel/image-assets?page=1

答案 1 :(得分:1)

您可以创建符号链接:

ln -s /path/to/laravel/resources/images /path/to/laravel/public/images

尽管其他用户已经指出,resource目录并不打算公开使用。

答案 2 :(得分:1)

您可以创建一条专门用于显示图像的路线。

Route::get('/resources/app/uploads/{filename}', function($filename){
    $path = resource_path() . '/app/uploads/' . $filename;

    if(!File::exists($path)) {
        return response()->json(['message' => 'Image not found.'], 404);
    }

    $file = File::get($path);
    $type = File::mimeType($path);

    $response = Response::make($file, 200);
    $response->header("Content-Type", $type);

    return $response;
});

现在您可以转到localhost / resources / app / uploads / filename.png,它将显示图像。
引用How to get image from resources in Laravel?
但是再说一次,不应使用resources文件夹存储图像。公共文件夹,静态资产(例如图像,js,css等)不应位于此位置。如@sehdev所说的那样。.

答案 3 :(得分:0)

您的问题的答案在Laravel的文档中:https://laravel.com/docs/5.7/helpers#method-app-path

$path = base_path('resources/path/to/img_dir');

答案 4 :(得分:0)

我同意@sehdev。

但是,如果您仍然想从resources目录中提供图片,这是可以完成工作的解决方案。

您认为:

<img src="/your-image" />

在途中:

Route::get('/your-image', function ()
{
   $filepath = '/path/to/your/file';

    $file = File::get($filepath);
    $type = File::mimeType($filepath);

    $response = Response::make($file, 200);
    $response->header("Content-Type", $type);
    $response->header("Content-Length", File::size($filepath));
    return $response;
})

这不是最佳解决方案。建议您将资产移到公共目录。

编辑:使用laravel函数。我建议不要从url中获取文件路径,因为它可能受Directory Traversal的约束。