Laravel如何验证上传文件数组总大小 实现多图总容量限制
Laravel 多文件上传总大小校验实现方案
当前Laravel 9/10/11版本不需要沿用5年前需要手动提取文件、独立注册验证器的繁琐方案,有两种非常轻量的实现方式,完全适配你在ProductController@store里的表单提交流程。
方案1:闭包规则(单场景快速实现,推荐)
直接在控制器的校验数组中写闭包校验逻辑,不需要额外生成文件,代码量最少:
// ProductController@store 方法内的校验逻辑 $validated = $request->validate([ // 先写商品本身的字段校验规则,按需调整 'title' => 'required|string|max:100', 'price' => 'required|numeric|min:0', 'description' => 'nullable|string', // 图片数组的基础规则 'images' => 'required|array|min:1', 'images.*' => 'image|mimes:jpg,jpeg,png,webp', // 单张图片的格式、单图大小规则写在这里 // 总大小校验直接加在images字段上 'images' => function (string $attribute, mixed $files, Closure $fail) { $totalBytes = collect($files)->sum(fn($file) => $file->getSize()); if ($totalBytes > 10 * 1024 * 1024) { // 10MB换算为字节 $fail('上传的所有图片总大小不能超过10MB'); } }, ]); // 校验通过后再执行业务逻辑 $product = Product::create($validated); // 批量写入关联图片记录 foreach ($validated['images'] as $image) { $path = $image->store('products/'.$product->id, 'public'); $product->images()->create(['path' => $path]); }
方案2:自定义规则类(多场景复用)
如果你的项目里还有其他多文件上传需要做总大小校验,可以生成一个通用规则类一次编写多处调用:
- 执行artisan命令生成规则文件
php artisan make:rule TotalUploadSize - 编辑规则类逻辑
// app/Rules/TotalUploadSize.php namespace App\Rules; use Closure; use Illuminate\Contracts\Validation\ValidationRule; class TotalUploadSize implements ValidationRule { /** * @param int $maxSizeMb 允许的总大小,单位MB */ public function __construct(protected int $maxSizeMb) {} public function validate(string $attribute, mixed $files, Closure $fail): void { $totalBytes = collect($files)->sum(fn($file) => $file->getSize()); if ($totalBytes > $this->maxSizeMb * 1024 * 1024) { $fail("上传文件总大小不能超过{$this->maxSizeMb}MB"); } } } - 校验时直接调用即可
'images' => ['required','array','min:1', new TotalUploadSize(10)], 'images.*' => 'image|mimes:jpg,jpeg,png,webp|max:2048', // 这里的max是单张图不超过2MB
注意事项
- 总大小规则必须绑定在文件数组字段(即示例中的
images)上,不要写在images.*的通配符规则里,后者只会对单张文件生效 - 不需要在业务逻辑里重复计算文件大小,校验不通过时Laravel会自动把错误信息返回到前端,和内置校验规则的行为完全一致
- 该方案兼容Laravel 6及以上所有版本,不需要引入第三方扩展包
内容的提问来源于stack exchange,提问作者Mostafa Said
相关产品推荐
相关产品推荐

