Spring 3.0 MultipartFile上传

我正在将Java Web应用程序转换为Spring框架,并对我在文件上载时遇到的问题提出一些建议。 原始代码是使用org.apache.commons.fileupload编写的。

  1. Spring MultipartFile是否包装了org.apache.commons.fileupload,或者我可以从我的POM文件中排除这种依赖关系?

  2. 我见过以下例子:

    @RequestMapping(value = "/form", method = RequestMethod.POST) public String handleFormUpload(@RequestParam("file") MultipartFile file) { if (!file.isEmpty()) { byte[] bytes = file.getBytes(); // store the bytes somewhere return "redirect:uploadSuccess"; } else { return "redirect:uploadFailure"; } } 

    最初我试图遵循这个例子,但总是得到一个错误,因为它找不到这个请求参数。 所以,在我的控制器中,我做了以下事情:

     @RequestMapping(value = "/upload", method = RequestMethod.POST) public @ResponseBody ExtResponse upload(HttpServletRequest request, HttpServletResponse response) { // Create a JSON response object. ExtResponse extResponse = new ExtResponse(); try { if (request instanceof MultipartHttpServletRequest) { MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; MultipartFile file = multipartRequest.getFiles("file"); InputStream input = file.getInputStream(); // do the input processing extResponse.setSuccess(true); } } catch (Exception e) { extResponse.setSuccess(false); extResponse.setMessage(e.getMessage()); } return extResponse; } 

它正在发挥作用。 如果有人能告诉我为什么@RequestParam不适合我,我会很感激。 顺便说一句,我确实有

     

在我的servlet上下文文件中。

  1. spring不依赖于commons-fileupload,所以你需要它。 如果它不存在,spring将使用其内部机制
  2. 您应该将MultipartFile作为方法参数传递,而不是@RequestParam(..)

我不得不

  1. 将commons-fileupload依赖项添加到我的pom,
  2. 添加multipartResolver bean(在问题中提到),
  3. 在handleFormUpload方法中使用@RequestParam(“file”)MultipartFile文件
  4. 在我的jsp中添加enctype:

让它工作。

这对我有用。

 @RequestMapping(value = "upload.spr", method = RequestMethod.POST) public ModelAndView upload(@RequestParam("file") MultipartFile file, HttpServletResponse response) { // handle file here } 

请求参数的常规sysntax是@RequestParam(value =“Your value”,required = true),模式请求参数用于获取Url的值。

在POST中,您只会在请求正文中发送参数,而不是在URL中(您使用@RequestParams)

这就是你的第二种方法有效的原因。

在Spring MVC 3.2中引入了对Servet 3.0的支持。 因此,如果使用早期版本的Spring,则需要包含commons-file upload。