2015-02-23 74 views
1

我想通過使用Spring MVC3上傳文件並進行處理。我試着用如何使用spring mvc3上傳文件?

@RequestMapping(value = "uploadAction.do") 
public ModelAndView upload(
@RequestParam("file") CommonsMultiPartFile file 
) 
{ 

System.out.println(file); 
ModelAndView view = new ModelAndView(); 
return view; 
} 

但它不工作,我有@RequestParam@ModelAttribute困惑,請幫我

+0

看看[這裏](http://stackoverflow.com/ questions/20162474/how-do-i-receive-a-file-upload-in-spring-mvc-using-both-multipart-form-and-chunk) – 2015-02-23 09:13:22

回答

2

上傳功能取決於se素質因素。如docs所示,以下是您必須確保的事項

發出POST請求。上傳文件應該是一個POST請求

@RequestMapping(value = "uploadAction.do", method=RequestMethod.POST) 

春季啓用分段處理通過添加一個multipart解析器到web應用程序的上下文

 <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> 
     <!-- one of the properties available; the maximum file size in bytes --> 
     <property name="maxUploadSize" value="100000"/> 
    </bean> 

確保公地fileupload.jar是你的classpath,如果你正在使用maven,以下內容應該覆蓋你

<!-- File Upload --> 
    <dependency> 
     <groupId>commons-fileupload</groupId> 
     <artifactId>commons-fileupload</artifactId> 
     <version>1.2.2</version> 
    </dependency> 
    <dependency> 
     <groupId>commons-io</groupId> 
     <artifactId>commons-io</artifactId> 
     <version>2.0.1</version> 
    </dependency> 

這一切的地方,你的映射應該很好地工作,提供您的形式是好的,這裏有一個例子

<form id="fileuploadForm" action="/uploadAction.do" method="POST" enctype="multipart/form-data" class="cleanform"> 
     <input id="file" type="file" name="file" /> 
     <p><button type="submit">Upload</button></p>   
    </form> 

還要注意它始終是更好的程序對一個接口,通過改變參數類型爲

public ModelAndView upload(@RequestParam("file") MultipartFile file) { 

你會委託注入實現框架。好處是你可以使用spring mvc測試框架編寫文件上傳測試,在這種情況下框架會插入嘲笑實現的MultipartFile界面

+0

Thanks,It works for me – 2015-02-23 11:40:05

0

事情是這樣的:

@RequestMapping(value="/upload", method=RequestMethod.POST) 
    public String upload(@RequestParam("upload") 
          MultipartFile multipartFile 
          ...       
){   
    .... 
} 

,並在表單的enctype是必需的:

<form id="command" name="command" method="POST" action="/upload" enctype="multipart/form-data"> 
    .... 
     <input id="upload" type="file" name="photo"> 
    .... 
</form>