Vue动态可新增表单多文件上传,如何将上传文件转为数组提交后端
Vue 动态多附件上传仅单文件提交问题修复方案
问题核心原因
你的代码存在3个关键错误导致仅最后一个文件能被提交:
- 循环变量和附件数组重名,上下文指向混乱
- 文件选择回调没有绑定当前行索引,选中的文件无法对应到数组的对应项,反复覆盖导致只剩最后一个文件有效
- 提交时直接用
JSON.stringify序列化包含File对象的数组,File对象无法被JSON序列化,后端无法识别有效文件数据
修复后的代码
页面模板代码
<div class="col-6"> <!-- 循环变量改名避免和数组重名,绑定index传给文件选择回调 --> <div class="row row g-3" v-for="(item, index) in attachmentList" :key="index"> <div style="font-size:13px">Attachment</div> <div class="col-sm-4"> <input type="text" v-model="item.att_name"> </div> <div class="col-sm-7"> <div class="col"> <!-- 把当前行index传给selectFile方法 --> <input type="file" @change="selectFile($event, index)"/> </div> </div> </div> <div style="margin-top: 15px;"> <button type="button" @click="addNewAttachment">Add Attachment</button> </div> </div> <!-- 提交按钮 --> <div style="margin-top:50px"> <button type="button" @click="onsubmit">Submit</button> </div>
逻辑代码
export default { name: 'bbb', data() { return { // 数组改名避免和循环变量重名 attachmentList: [ { att_name: '', att_file: '', } ], } }, methods: { // 接收index参数,给对应行的附件项赋值文件 selectFile(e, index) { const selectedFile = e.target.files[0]; this.attachmentList[index].att_file = selectedFile; }, addNewAttachment() { this.attachmentList.push( { att_name: '', att_file: '', } ); }, onsubmit() { const data = new FormData(); // 遍历所有附件,逐个添加到FormData,不要JSON序列化File对象 this.attachmentList.forEach((item, index) => { data.append(`attachments[${index}][att_name]`, item.att_name); data.append(`attachments[${index}][att_file]`, item.att_file); }) // 这里调用你的接口把FormData传给后端即可,注意请求头要设为multipart/form-data(大部分请求库传FormData会自动设置) } } }
额外说明
- 后端接收时可以直接按
attachments数组格式读取,每个数组项包含att_name和att_file两个字段 - 不要尝试用JSON序列化包含File对象的变量,文件数据必须通过FormData单独传输
- 原表单预览图如下:

内容的提问来源于stack exchange,提问作者Jon
相关产品推荐
相关产品推荐

