简体   繁体   中英

Multiple file upload using ajax and spring mvc returns 404

I am trying to upload multiple file using ajax and spring mvc.

var ajaxData = new FormData();
for(var j=0;j<files.length;j++){
    ajaxData.append('file', files[j]);
}
$http.post(url, ajaxData, {
    headers: {'Content-Type': undefined},
    transformRequest: angular.identity
}).success(function(response) {
    console.log(response);
});

Spring Controller:

@RequestMapping(value = "/save", produces="application/json")
public String save(
        @RequestParam(value="file") ArrayList<MultipartFile> uploadFiles) throws IllegalStateException, IOException, JSONException, Exception {
    JSONArray j = new JSONArray();
    for (MultipartFile uploadFile : uploadFiles) {
        if(uploadFile!=null){
            uploadFile.transferTo(new File(saveToDirectory+uploadFile.getOriginalFilename()));
            j.put(uploadFile.getOriginalFilename());
        }
    }
    JSONObject result = new JSONObject();
    result.put("files", j);
    return result.toString();
}

I can see that files are successfully uploaded to the directory. However, the ajax request fails to complete and throws 404 (not found) exception.

POST http://localhost:8080/app/save 404 (Not Found)

Having hard time finding bug.

It was a silly mistake. I forgot to add @ResponseBody annotation to controller function. Controller method should look like this:

@RequestMapping(value = "/save", produces="application/json")
@ResponseBody
public String save(
        @RequestParam(value="file") ArrayList<MultipartFile> uploadFiles) throws IllegalStateException, IOException, JSONException, Exception {
     ....    
}

Closing the question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM