java笔记_7_文件上传到后端
html代码
<div id="fileDiv" style="width:150px"><input type="file" multiple></div>
jsp代码
var uploadFileParam = new FormData(); var fileList = p.next().next().next().next().next().next().next().next().children()[0].children[0].files;
//formData传文件列表 for (var i = 0; i < fileList.length; i++) { uploadFileParam.append("fileList",fileList[i]); } $.ajax({ url: apiBaseUrl + '/api/xxxxxx', type: 'post', async: false,//同步 data: uploadFileParam, processData:false, //必写 contentType:false, //必写 success:function(json){ console.log(json); }, error:function(json){ layer.msg( '上传附件接口调用失败,请重新提交!'); } })
java代码
@ApiOperation("上传百融授权书文件") @PostMapping("/api/br/uploadFile") public Result uploadFile(@RequestParam(value = "fileList", required = false) MultipartFile[] fileList) { return brService.uploadFile(fileList); }
遇到的报错
报错1 前后端都用post,但是提示org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'GET' not supported //修改前端ajax processData:false, //必写 contentType:false, //必写 报错2 org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'multipart/form-data;boundary=----WebKitFormBoundarycnssyBEF3LcB1jH8;charset=UTF-8' not supported //修改后端Controller @RequestBody不支持form-data,直接去掉注解 我是把Controller 的入参改用 @RequestParam(不能用聚合的对象)
报错3
后端接收的文件为null
@RequestParam后面直接跟具体对象,可传多个@RequestParam
报错4
前端直接append文件数组,传入的数据不对,要遍历append,append可传相同属性名,组成一个集合,set直接覆盖原数据
uploadFileParam.append("fileList",fileList[i]);