Spring MVC使用AJAX一次上传多个文件不起作用 [英] Spring mvc upload multiple files at once with AJAX doesn't work
问题描述
我正在使用Spring boot 2.0.1,并且尝试使用dropzone上传多个文件。当我在 Dropzone.js
上使用 uploadMultiple:false
时,一切运行正常。当我设置 uploadMultiple:true
时,我的控制器停止工作。
I'm using Spring boot 2.0.1 and I'm trying to upload multiple files with dropzone. Everything is working perfectly when I'm using uploadMultiple: false
on Dropzone.js
. When I set uploadMultiple: true
, My Controller stops working.
控制器类如下:
@PostMapping(value = "/img/upload")
public ResponseEntity<?> fileUpload(@RequestParam("file") MultipartFile[] files){
System.out.println(files.length);
for (MultipartFile file : files) {
try {
file.transferTo(new File("/opt/img/" + file.getOriginalFilename()));
System.out.println(file.getOriginalFilename());
} catch (IOException e) {
e.printStackTrace();
}
}
return new ResponseEntity<>("File Uploaded Successfully.", HttpStatus.OK);
}
文件大小不超过1MB,我的设置为
The files are no more than 1MB and my settings are
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB
我上传文件时的请求标头:
My request header when I upload the files:
------WebKitFormBoundaryihPcX9WHR5UA9jGD
Content-Disposition: form-data; name="file[0]"; filename="cars-02-01.png"
Content-Type: image/png
------WebKitFormBoundaryihPcX9WHR5UA9jGD
Content-Disposition: form-data; name="file[1]"; filename="Screenshot from 2018-05-03 23-31-53.jpg"
Content-Type: image/jpeg
一切似乎都很完美。我仍然找不到导致此问题的原因?
Everything seems perfect. I still cannot find the reason for this problem?
推荐答案
似乎我应该使用 MultipartHttpServletRequest
,而不是 MultipartFile []文件
。我将方法更改为:
It seems that I should use the MultipartHttpServletRequest
instead of MultipartFile[] files
. I Changed the method to:
@PostMapping(value = "/img/upload")
public ResponseEntity<?> fileUpload(MultipartHttpServletRequest request) {
Map<String, MultipartFile> fileMap = request.getFileMap();
for (MultipartFile file : fileMap.values()) {
try {
file.transferTo(new File("/opt/img/" + file.getOriginalFilename()));
System.out.println(file.getOriginalFilename());
} catch (IOException e) {
e.printStackTrace();
}
}
return new ResponseEntity<>("File Uploaded Successfully.", HttpStatus.OK);
}
这篇关于Spring MVC使用AJAX一次上传多个文件不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!