Laravel:无法从Storage中获取图片的问题求助
看起来你遇到的核心问题是存储的图片不在Web可访问的目录下,加上代码顺序和路径配置的小问题,导致Blade模板无法加载图片。我来一步步帮你解决:
一、核心原因
Laravel的storage/app目录默认是不对外暴露的——Web服务器只会把public目录作为根目录,所以直接通过asset('storage/app/images/...')访问是找不到文件的。你的文件系统配置里,public磁盘才是专门用来存储公开可访问文件的(指向storage/app/public),但你现在用的是local磁盘存在了storage/app/images,自然无法被Web访问。
另外,你的存储代码顺序有问题:先获取了文件名再判断是否有上传文件,如果用户没传图片,$image变量会直接报错,这也是需要修正的。
二、分步解决方案
1. 修正存储代码,改用public磁盘存储
把图片存到public磁盘对应的目录(storage/app/public/images),这样后续可以通过符号链接让Web访问到。修改后的代码如下:
$filename = null; // 默认设为null,避免无图片时报错 if ($request->hasFile('image')) { $image = $request->file('image'); $filename = $image->getClientOriginalName(); // 指定使用public磁盘存储,文件会被放到storage/app/public/images $image->storeAs('images', $filename, 'public'); } $creator = new Content_form([ 'media_id' => $request->get('media_name'), 'content_title' => $request->get('content_title'), 'content_description' => $request->get('content_description'), 'date_occured' => \Carbon\Carbon::now()->format('Y-m-d'), 'page_number' => $request->get('page_number'), 'image' => $filename, ]); $creator->save();
2. 创建Storage符号链接
Laravel提供了命令,把storage/app/public目录映射到public/storage,这样Web服务器就能访问到存储的文件了。在终端执行:
php artisan storage:link
执行成功后,你会在public目录下看到一个storage的符号链接,指向storage/app/public。
3. 修改Blade模板的图片路径
现在图片存在storage/app/public/images,通过符号链接对应到public/storage/images,所以Blade里的路径要改成:
@foreach($pendingNews as $number=> $post) <td style="font-size: 16px; width: 210px"> <img class="img-rounded" width="150" height="130" src="{{ asset('storage/images/'.$post->image) }}"> </td> @endforeach
三、可选方案(不推荐,但适合不想改存储路径的场景)
如果你坚持要把图片存在storage/app/images,可以手动创建符号链接把这个目录映射到public目录下:
- Linux/Mac:在项目根目录执行
ln -s $(pwd)/storage/app/images $(pwd)/public/images - Windows:以管理员身份打开命令提示符,执行
mklink /D "C:\你的项目路径\public\images" "C:\你的项目路径\storage\app\images"
然后Blade里直接用asset('images/'.$post->image)即可。不过这种方式不符合Laravel的文件系统设计规范,优先推荐第一种方案。
内容的提问来源于stack exchange,提问作者fetty

