<!—配置文件上傳解釋器 --> <mvc:annotation-driven></mvc:annotation-driven> <bean name="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value="UTF-8"></property> <property name="maxInMemorySize" value="512000000" ></property> <property name="maxUploadSize" value="20000000"></property> </bean>
@RequestMapping(value="upload") public String upload(MultipartFile file) throws Exception{ File destfile = new File("D:/dir/" + file.getOriginalFilename()); file.transferTo(destfile); return "/upload.jsp"; }
注意:spring MVC文件上傳功能引用了commons-fileupload組件,實現文件上傳功能須要引入commons-fileupload和commons-io包前端
(前端頁面很簡單,就是一個用來上傳文件的input標籤,但要注意標籤的name屬性要和映射方法的參數名對應,如「file」)web
@RequestMapping(value="upload") public String upload(MultipartFile[] file) throws Exception{ for (MultipartFile file : files) { File destfile = new File("D:/dir/" + file.getOriginalFilename()); file.transferTo(destfile); } return "/upload.jsp"; }
@RequestMapping(value="/{filename}/download") public void download(@PathVariable String filename,HttpServletResponse response) throws Exception{ File file=new File("d:/dir/"+filename); FileInputStream input = new FileInputStream(file); ServletOutputStream out = response.getOutputStream(); response.addHeader("Content-Disposition", "attachment;filename="+new String(filename.getBytes(),"ISO-8859-1")); IOUtils.cope(input,out); }
(注:文件下載須要修改應答頭信息,將流以附件形式輸出,並設置文件名的編碼格式爲ISO-8859-1)spring
———————————————————————————————————————————————————————————————————mvc
The end @ 萬有引力+
app
-框架
-jsp
-post
-編碼
-spa