Upload multiple files using ajax and spring mvc

I am trying to upload tiered files using FormData and spring.

HTML:

<input type="file" name="img" multiple id="upload-files"> 

JS Code:

 var ajaxData = new FormData(); var files = $('#upload-files').prop('files'); for(var i=0;i<files.length;i++){ ajaxData.append('file['+i+']', files[i]); } ajaxData.append("file", files); $http.post('../rest/upload', ajaxData, { headers: {'Content-Type': undefined }, transformRequest: angular.identity }); 

Spring Controller Code:

 @RequestMapping(value = "/upload", produces="application/json", method = RequestMethod.POST) @ResponseBody public String upload( @RequestParam ArrayList<MultipartFile> files ){ System.out.println(files.size()); return null; } 

However, the number of files exits equal to 0 when sending a request with several files. When using array notation of MultipartFile[] files instead of ArrayList, it gives 400, Bad Request.

How to make spring controller work with multiple files? I can not find a solution to other SO issues.

+7
java jquery spring ajax spring-mvc
source share
1 answer

By default, the DataBinder tries to bind the request parameters to the target using an agreement - the parameter names from the request (FormData in your case) must match in the controller action.

In your case, you should rename file[i] to files[i] :

 for(var i=0; i < files.length; i++){ ajaxData.append('files[' + i + ']', files[i]); } 

OR rename the action parameter from ArrayList<MultipartFile> files to ArrayList<MultipartFile> file


Also, delete this line ajaxData.append("file", files); (which is right after the for loop) because it sets a parameter with the same name and some kind of failure may occur.

Hope this helps.

+4
source share

All Articles