基於Spring MVC的文件上傳和下載功能的實現

  配置文件中配置掃描包,以便建立各個類的bean對象web

    <context:component-scan base-package="com.neuedu.spring_mvc"></context:component-scan>spring

1、文件的上傳

  Spring MVC 上下文中默認沒有爲文件上傳提供了直接的支持,所以默認狀況下不能處理文件的上傳工做數組

    若是想使用 Spring 的文件上傳功能,需如今上下文中配置 CommonsMultipartResovler:tomcat

  一、加入jar包:
      commons-fileupload-1.3.1.jar
      commons-io-2.4.jarsession

    Maven項目經過在pom.xml文件中配置jar包依賴mvc

 1     <dependency>
 2     <groupId>commons-fileupload</groupId>
 3     <artifactId>commons-fileupload</artifactId>
 4     <version>1.3.1</version>
 5   </dependency>
 6   <dependency>
 7     <groupId>commons-io</groupId>
 8     <artifactId>commons-io</artifactId>
 9     <version>2.4</version>
10   </dependency>        

  二、在SpringMVC配置文件中配置CommonsMultipartResovlerapp

1   <!-- 配置CommonsMultipartResolver,必須配置id值爲multipartResolver -->
2   <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
3     <property name="defaultEncoding" value="utf-8"></property>
4     <!-- 以字節爲單位 -->
5     <property name="maxUploadSize" value="1024000"></property>
6   </bean>

  三、表單的設置dom

    POST請求,file類型,enctype="multipart/form-data"webapp

1   <form action="${pageContext.request.contextPath}/upload" method="post" enctype="multipart/form-data">
2         文件:<input type="file" name="file"/>
3         描述:<input type="text" name="desc"/>
4         <input type="submit" value="上傳"/>
5     </form>

  四、上傳的實現post

 1 @Controller  2 public class TestController {  3     @RequestMapping(value="/upload",method=RequestMethod.POST)  4     public String upload(@RequestParam(value="desc") String desc,  5             @RequestParam(value="file") CommonsMultipartFile file,HttpServletRequest request) throws IOException{  6         ServletContext context = request.getSession().getServletContext();  7         //獲取真實路徑,使用tomcat插件,默認路徑爲webapp下
 8         String realPath = context.getRealPath("/upload");  9         
10         //判斷upload文件夾是否存在
11         File file1=new File(realPath); 12         if(!file1.exists()){ 13  file1.mkdir(); 14  } 15         
16         //文件名添加uuid,防止重複
17         String uuid=UUID.randomUUID().toString().replace("-", ""); 18         String fileName=uuid+"_"+file.getOriginalFilename(); 19         //獲取輸入流
20         InputStream in=file.getInputStream(); 21         //獲取輸出流,指定輸出路徑及文件名
22         FileOutputStream out=new FileOutputStream(new File(realPath+"\\"+fileName)); 23  IOUtils.copy(in, out); 24  out.close(); 25  in.close(); 26         return "success"; 27  } 28 }

2、文件的下載

  用ResponseEntity<byte[]> 返回值完成文件下載

 1 @Controller  2 public class TestController {  3     @RequestMapping(value="/download")  4     public ResponseEntity<byte[]> download(HttpSession session) throws IOException{  5         byte[] body=null;  6         ServletContext context = session.getServletContext();  7         String fileName="d5b9b61dc7154f5c9df4c844348ef6df_fennu.jpg";  8         
 9         //獲取文件路徑
10         String filePath = context.getRealPath("/upload/"+fileName); 11         //讀取文件內容
12         InputStream in=new FileInputStream(new File(filePath)); 13         //建立文件字節數組,數組長度爲文件的總大小
14         body=new byte[in.available()]; 15         //將文件內容保存到字節數組中
16  in.read(body); 17         
18         //建立響應頭信息的MultiValueMap
19         MultiValueMap<String, String> headers=new HttpHeaders(); 20         //設置文件名從新編碼,以gbk格式讀取再編碼爲iso8859-1
21         fileName=new String(fileName.getBytes("gbk"), "iso8859-1"); 22         //設置響應信息
23         headers.add("Content-Disposition", "attachment;filename="+fileName); 24         
25         HttpStatus statusCode=HttpStatus.OK; 26         ResponseEntity<byte[]> responseEntity=new ResponseEntity<byte[]>(body, headers, statusCode); 27  in.close(); 28         return responseEntity; 29  } 30 }
相關文章
相關標籤/搜索