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

Laravel使用Intervention Image调整大小时如何自动创建thumb文件夹

问题根源

报错是因为thumb目录不存在,且你把创建目录的逻辑给注释了,同时原有注释的目录创建逻辑本身也存在缺陷,才会导致写入文件失败。

修复要点

  • 取消目录创建逻辑的注释,给mkdir添加第三个参数true开启多级目录递归创建,同时设置目录权限为0755保证写入权限
  • 所有路径统一用public_path()定位到项目公开目录,避免相对路径定位错误
  • 补全原始图片的上传逻辑,同时保留缩略图生成逻辑

修复后完整代码

protected function articleUploadImage($file, $folder, $size)
{
    $d = jdate();
    $year = $d->format('Y');
    $month = $d->format('m');
    $day = $d->format('d');

    $direct = 'storage/upload/images/'. $folder . '/' . $year . '/' . $month . '/' . $day;
    $directWithResize = $direct . '/thumb';
    $extension = $file->getClientOriginalExtension();
    $fileName = Str::random(20) . time() . '.' . $extension;

    // 递归创建各级目录并设置权限
    if (!is_dir(public_path($directWithResize))) {
        mkdir(public_path($directWithResize), 0755, true);       
    }

    // 上传原始尺寸图片
    $file->move(public_path($direct), $fileName);

    // 生成并保存缩略图
    Image::make($file->getRealPath())->fit($size, null, function ($constraint) {
        $constraint->aspectRatio();
    })->save(public_path($directWithResize  . '/' . $fileName));
    
    return $direct;
}

额外注意事项

  • 要确保storage目录和public目录的所属用户和web运行用户一致,避免权限不足导致写入失败
  • 如果是Laravel框架的项目,建议优先用框架自带的Storage facade处理文件存储,避免手动处理路径的问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 22:24:02