You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel存储中上传文件后如何保存完整路径?

解决Laravel上传图片后数据库保存完整路径的问题

要让数据库保存images/blogs/1650953308.jpg这类完整相对路径,只需调整代码中$fileNameService的赋值逻辑,确保它包含路径前缀而非仅文件名即可,修改后的代码如下:

public function store(Request $request)
{
    $fileNameService = null;
    $pathPrefix = 'images/blogs/'; // 定义相对路径前缀

    if ($request->hasFile('image'))
    {
        $file = $request->file('image');
        $name = time();
        $extension = $file->getClientOriginalExtension();
        // 拼接完整相对路径赋值给$fileNameService
        $fileNameService = $pathPrefix . $name . '.' . $extension;
        
        $img = Image::make($file->path());
        $img->resize(600, 300, function ($constraint) {
            $constraint->aspectRatio();
        })->save('storage/' . $fileNameService); // 用完整路径保存文件
    }

    Blog::query()->create([
        'image' => $fileNameService,
    ]);

    return redirect()->route('admin.blogs.index');
}

关键修改点:

  • 新增$pathPrefix变量统一管理路径前缀,让代码更易维护
  • 将$fileNameService从单纯的文件名,改为包含images/blogs/前缀的完整相对路径
  • 保存文件时,路径调整为storage/ + 完整相对路径,确保文件存储到正确的目录下

额外提示:

如果需要前端能直接访问上传的图片,需执行Laravel的存储链接命令,将storage/app/public目录链接到项目根目录的public/storage:

php artisan storage:link

之后前端可通过asset('storage/' . $blog->image)生成图片访问URL。

内容的提问来源于stack exchange,提问作者Mahmoud Khosravi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 00:57:13