cha*_*nie 2 ajax spring file-upload jquery-file-upload
我无法通过AJAX从我的网络客户端上传文件到我的服务器.我在客户端使用以下jQuery库来进行文件上传: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
}
Run Code Online (Sandbox Code Playgroud)
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
}
Run Code Online (Sandbox Code Playgroud)
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?
您可以尝试将方法的签名更改为
@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();
...
}
...
}
Run Code Online (Sandbox Code Playgroud)
这适用于我们的webapp中的jQuery文件上传.如果由于某种原因这对您不起作用,您可以尝试通过检查jQuery文件上载(例如,使用Fiddler)发出的HTTP请求并从Spring DispatcherServlet开始调试响应来隔离问题.
| 归档时间: |
|
| 查看次数: |
737 次 |
| 最近记录: |