前端上传多个文件给后端示例

后端代码:

@RequestMapping(value = "primaryAudit")  
@ResponseBody  
public CResponse primaryAuditKeywordRisk(KeyWordRiskEditDto dto, MultipartFile[] files) {  
    try {    
     return CResponse.OK;  
    } catch (Exception e){  
     return CResponse.error(e.getMessage());  
    }  
  }
}

前端代码: 数据部分: 两个file数组。

amazonfileList:[],  
amazonfiles:[]

组件部分代码:

<el-upload  
ref="uploadImg"  
list-type="picture"  
drag  
action=""  
:file-list="amazonfileList"  
:limit="1"  
:http-request="uploadAmazon"  
:auto-upload="true"  
style="width: 50%"  
>  
<i class="el-icon-upload"></i>  
<div class="el-upload__text">只能上传图片,将文件拖到此处,或<em>点击上传</em></div>  
</el-upload>

上传时调用uploadAmazon事件,把file传到amazonfiles中。

uploadAmazon(param){  
  this.amazonfile = param.file  
},

正式上传给后端接口:

let formData = new FormData();
//这些是组装成DTO的基本信息
formData.append("id", this.keywordEditDto.id);  
formData.append("remark", this.keywordEditDto.remark);  


// 逐个将文件添加到 FormData 中
this.amazonfiles.forEach(file => { formData.append('amazonFiles', file); });
  
let _this = this  
$.ajax({  
  type: "POST",  
  url: "/audit/primaryAudit",  
  enctype: 'multipart/form-data',  
  data: formData,  
  processData: false,  
  contentType: false,  
  cache: false,//上传文件无需缓存  
  timeout: 600000,  
  success: function (respData) {  
   if(respData.code == 0) {  
      this.message.success('上传成功')  
   }else{  
      this.message.error(respData.message)  
   } 
  },  
  error: function (xhr, textStatus) {   
    this.message.error("请求异常!")  
  }  
});

有疑问请移步到企鹅私信: 技术交流