8

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.

2
  • Did you try to relocate List<MultipartFile> to an object and configured CommonsMultipartResolver and InternalResourceViewResolver on spring-servlet.xml? Commented Aug 12, 2015 at 20:39
  • Did you add encType properly in form submit button? e.g. <form enctype="multipart/form-data" action="uploadFile.jsp" method="POST"> and input type as <input type="file" name="file[]" multiple /> Commented Sep 18, 2015 at 14:38

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.