Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upload multiple files using ajax and spring mvc

I am trying to upload multile 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, count of files is coming out to be 0 on submitting the request with multiple files. On using array notation MultipartFile[] files instead of ArrayList , it gives 400, Bad Request.

How to make spring controller work with multiple files? I am unable to find solution on other SO questions.

like image 957
Gautam Kumar Avatar asked Aug 11 '15 15:08

Gautam Kumar


1 Answers

By default, the DataBinder tries to bind request parameters to target object with convention - the parameter names from the request (the FormData in your case) and in the controller's action must match.

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 action's 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 is setting a parameter with the same name and some kind of glitch can occur.

Hope this helps.

like image 101
Viktor Bahtev Avatar answered Nov 13 '22 07:11

Viktor Bahtev