首页 > 解决方案 > Laravel 显示来自 storage/app/public 的图像

问题描述

我正在尝试显示 storage/app/public 文件夹中的图像。每当我的控制器从这个文件夹中检索图像时

$images = Storage::files('public');

从此处检索的文件以 为前缀public/,而不是storage/。这导致的问题是可以找到图像localhost/storage/filename.jpg,但无法使用localhost/public/filename.jpgor找到图像localhost/storage/public/filename.jpg。我可以通过手动切断公共前缀并将其替换为存储来解决此问题,但这并不是一种特别优雅的做事方式。

我已经运行了命令 php artisan storage:link 并重新运行它会产生一条The "public/storage" directory already exists.消息。

标签: phplaravel-bladelaravel-5.6

解决方案


publicLaravel在存储配置中带有一个内置磁盘。

要列出文件storage/app/public夹中不带前缀的所有文件,请使用:

\Storage::disk('public')->files();

要获取文件storage/app/public夹内文件的正确 URL,请使用:

\Storage::disk('public')->url($file);

要返回文件夹内文件的 URL 数组storage/app/public,下面是一个示例组合:

array_map(function ($f) {
    return \Storage::disk('public')->url($f);
}, \Storage::disk('public')->files());

推荐阅读