问题
I am having trouble uploading files via AJAX from my web-client to my Server. I am using the following jQuery library in the client-side to do the file upload: https://github.com/hayageek/jquery-upload-file
In the server-side, I'm using Spring Framework and I have followed the following Spring Tutorial to build my Service: https://spring.io/guides/gs/uploading-files/
At first, my server method looked like this (file was defined as @RequestParam):
@RequestMapping(value="/upload", method=RequestMethod.POST)
public @ResponseBody String handleFileUpload(@RequestParam("file") MultipartFile file){
//functionality here
}
but every time I submitted the Upload form I got a Bad Request message from the Server, and my handleFileUpload()
method was never called.
After that, I realized the file was not being sent as a Request Parameter so I defined file
as @RequestBody, and now my method looks like this:
@RequestMapping(value="/upload", method=RequestMethod.POST)
public @ResponseBody String handleFileUpload(@RequestBody("file") MultipartFile file){
//functionality here
}
Now handleFileUpload()
is called every time the Upload form is submitted, but I am getting a NullPointerException
every time I want to manipulate file.
I want to avoid submitting the form by default, I just want to do it through AJAX straight to the Server. Does anybody know what could be happening here?
回答1:
you may try changing the signature of the method to
@RequestMapping(value="/upload", method=RequestMethod.POST)
public @ResponseBody String handleFileUpload(MultipartHttpServletRequest request){
Iterator<String> iterator = request.getFileNames();
while (iterator.hasNext()) {
String fileName = iterator.next();
MultipartFile multipartFile = request.getFile(fileName);
byte[] file = multipartFile.getBytes();
...
}
...
}
this works with jQuery File Upload in our webapp. If for some reason this does not work for you, you may try to isolate the problem, by inspecting the HTTP request issued by the jQuery File Upload (for example, with Fiddler), and debugging the response starting from Spring DispatcherServlet.
来源:https://stackoverflow.com/questions/27772803/uploading-files-using-the-spring-framework-and-jquery-upload-file-plugin-issue