2012-05-10 45 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,則需要包含公共文件上傳。

相關問題