2012-05-10 59 views
3

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

  1. 春天在什么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"; 
        } 
    } 
    

    本来我想以此为榜样,但总是得到一个错误,因为它找不到此请求PARAM。所以,在我的控制器我已经做了以下:

    @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不适合我,我会很感激。顺便说一句我有

<bean id="multipartResolver" 
     class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> 
     <property name="maxUploadSize" value="2097152"/> 
    </bean> 

在我的servlet上下文文件。

回答

0

请求参数的一般sysntax是这个@RequestParam(value =“Your value”,required = true), 请求模式通过请求参数获取URL的值frm。

2
  1. spring不依赖commons-fileupload,所以你需要它。如果它不存在春天将使用其内部机制
  2. 你应该通过一个MultipartFile作为方法参数,而不是@RequestParam(..)
+0

你是什么意思将它作为方法参数传递?谁将从请求中提取它并将其提供给该方法? – Gary

+5

春天会... :) – Bozho

1

这对我的作品。

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

我不得不

  1. 添加公地文件上传依赖于我的POM,
  2. 添加multipartResolver豆(在问题中提到),
  3. 使用@RequestParam( “文件”)MultipartFile文件中的handleFormUpload方法和
  4. 在我的jsp中添加enctype:<form:form method="POST" action="/form" enctype="multipart/form-data" >

让它起作用。

0

在POST你只会发送PARAMS在请求主体,而不是在URL(您使用@RequestParams)

这就是为什么你的第二个方法奏效。

0

在Spring MVC 3.2中引入了对Servet 3.0的支持。因此,如果您使用较早版本的Spring,则需要包含公共文件上传。

相关问题