Spring mvc upload multiple files at once with AJAX doesn't work

淺唱寂寞╮ 提交于 2019-12-13 00:35:11

问题


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.

The controller class is as follow:

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

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?


回答1:


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


来源:https://stackoverflow.com/questions/50320177/spring-mvc-upload-multiple-files-at-once-with-ajax-doesnt-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!