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

Laravel框架单文件上传功能改造为批量多文件上传的实现方法

多文件上传代码调整方案

1. 前端表单修改

首先调整上传控件的name属性,增加数组标识[]才能让后端接收到完整的多文件数组,同时可以删掉重复声明的PUT请求冗余代码,修改后代码如下:

<form action="{{ route('Listingimages.store', $listing->id) }}" method="POST" enctype="multipart/form-data">
    {{csrf_field()}}
    {{method_field('PUT')}}
    <label>Insert image</label>
    <input type="file" name="image[]" id="files" class="form-control" multiple>
    <!-- 补充提交按钮 -->
    <button type="submit" class="btn btn-primary">上传</button>
</form>

注:原代码中同时写了隐藏input的_method和method_field('PUT'),功能重复保留任意一个即可。


2. 后端控制器修改

调整验证规则适配数组格式,循环遍历每个上传文件分别处理存储,同时优化文件名生成规则避免批量上传时重名覆盖,修改后代码如下:

public function store(Request $request, $id) {
    $request->validate([
            'image' => 'required|array',
            'image.*' => 'required|file|mimes:jpg,jpeg,png,gif|max:2048', // 可按需调整格式和大小限制
    ]);

    $listing = Listing::findOrFail($id);

    if ($request->hasFile('image')) {
        foreach ($request->file('image') as $file) {
            $image = new Listingimage();
            $extention = $file->getClientOriginalExtension();
            // 拼接uniqid避免批量上传时time()生成的文件名重复
            $filename = time() . '_' . uniqid() . '.' . $extention;
            $file->move('assets/images/listingimages/', $filename);
            $fileOriginalName = $file->getClientOriginalName();
            
            $image->listing_id = $id;
            $image->image_url = $filename;
            $image->nom_image = $fileOriginalName;
            $image->save();
        }
    }

    return redirect()->back();
}

核心改动说明

  • 前端上传控件name属性改为数组格式image[],匹配多文件传输的参数规则
  • 后端验证新增数组校验规则,对每个上传的文件单独做格式、大小校验
  • 将原单文件的存储、数据写入逻辑包裹在foreach循环中,每个文件对应生成一条数据库记录
  • 文件名新增随机唯一标识uniqid(),避免短时间内批量上传时,time()生成的时间戳相同导致文件覆盖

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 14:54:07