Spring mvc使用AJAX一次上传多个文件并不起作用

时间:2018-05-13 20:05:44

标签: ajax spring-mvc tomcat dropzone.js dropzone

我使用的是Spring boot 2.0.1,我尝试使用dropzone上传多个文件。当我在uploadMultiple: false上使用Dropzone.js时,一切正常。当我设置uploadMultiple: true时,我的控制器停止工作。

控制器类如下:

@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,我的设置为

spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB

上传文件时的我的请求标题:

------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

一切似乎都很完美。我还是找不到这个问题的原因?

1 个答案:

答案 0 :(得分:1)

我似乎应该使用MultipartHttpServletRequest代替MultipartFile[] files。我将方法更改为:

@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);
}