天天看點

Spring MVC實作檔案的上傳和下載下傳的功能

<?xml version="1.0" encoding="UTF-8"?>
 2 <!-- 到入xml檔案的限制 -->
 3 
 4 <beans xmlns="http://www.springframework.org/schema/beans"
 5     xmlns:context="http://www.springframework.org/schema/context"
 6     xmlns:mvc="http://www.springframework.org/schema/mvc"
 7     xmlns:p="http://www.springframework.org/schema/p"
 8     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 9     xsi:schemaLocation="http://www.springframework.org/schema/beans
10      http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
11      http://www.springframework.org/schema/context
12      http://www.springframework.org/schema/context/spring-context-4.1.xsd
13       http://www.springframework.org/schema/mvc
14      http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
15      ">
16       
17       <!-- 開啟注解掃描(将對象納入spring容器) -->
18       <context:component-scan base-package="org.guangsoft.controller">
19       </context:component-scan> 
20       
21      <!-- 開始springmvc的映射注解和适配注解 -->
22      <mvc:annotation-driven></mvc:annotation-driven>
23      
24      
25      <!-- 執行個體化檔案上傳的解析器(MIME) -->
26      <bean id="multipartResolver" 
27          class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
28          <property name="defaultEncoding" value="utf-8"></property><!-- 用戶端發送資料的編碼 -->
29          <property name="maxUploadSize" value="5242880"></property><!-- 上傳檔案的大小 -->
30          <property name="uploadTempDir" value="/upload"></property>
31      </bean>
32      
33 </beans>       
Spring MVC實作檔案的上傳和下載下傳的功能

1.3建立FileController

Spring MVC實作檔案的上傳和下載下傳的功能
1 package org.guangsoft.controller;
 2 import java.io.File;
 3 import java.io.IOException;
 4 import java.util.UUID;
 5 import javax.servlet.http.HttpSession;
 6 import org.apache.commons.io.FileUtils;
 7 import org.springframework.http.HttpHeaders;
 8 import org.springframework.http.HttpStatus;
 9 import org.springframework.http.MediaType;
10 import org.springframework.http.ResponseEntity;
11 import org.springframework.stereotype.Controller;
12 import org.springframework.web.bind.annotation.RequestMapping;
13 import org.springframework.web.bind.annotation.RequestParam;
14 import org.springframework.web.multipart.commons.CommonsMultipartFile;
15 @Controller
16 public class FileController
17 {
18     /***
19      * 實作檔案的上傳
20      * 
21      * @RequestParam:指定用戶端發送資料的名字
22      * **/
23     @RequestMapping("/uploadFile")
24     public String uploadFile(@RequestParam("cmf") CommonsMultipartFile cmf,
25             HttpSession session)
26     {
27         // 1獲得上傳的檔案内容
28         byte[] bytes = cmf.getBytes();
29         // 2獲得upload的絕對路徑
30         String path = session.getServletContext().getRealPath("/upload");
31         // 3在伺服器的upload目錄下建立File對象
32         String oname = cmf.getOriginalFilename(); // 上傳檔案的原始名字
33         String uuid = UUID.randomUUID().toString();
34         File file = new File(path, uuid
35                 + oname.substring(oname.lastIndexOf(".")));
36         // 4将上傳的檔案拷貝到指定的目錄
37         try
38         {
39             FileUtils.writeByteArrayToFile(file, bytes);
40         }
41         catch (IOException e)
42         {
43             e.printStackTrace();
44         }
45         return "index.jsp";
46     }
47     /***
48      * 實作檔案下載下傳
49      * ***/
50     @RequestMapping("/download")
51     public ResponseEntity download(HttpSession session)
52     {
53         // 用來封裝響應頭資訊
54         HttpHeaders responseHeaders = new HttpHeaders();
55         // 下載下傳的附件的類型
56         responseHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
57         // 下載下傳的附件的名稱
58         responseHeaders.setContentDispositionFormData("attachment", "1.png");
59         String path = session.getServletContext().getRealPath("/upload");
60         String fname = "b8abd107-ecdd-49ae-9175-b39f1d18a288.png"; // 資料庫查詢獲得
61         // 将下載下傳的檔案封裝流對象
62         File file = new File(path, fname);
63         try
64         {
65             /**
66              * arg1:需要響應到用戶端的資料 arg2:設定本次請求的響應頭 arg3:響應到用戶端的狀态碼
67              * ***/
68             return new ResponseEntity(FileUtils.readFileToByteArray(file),
69                     responseHeaders, HttpStatus.CREATED);
70         }
71         catch (IOException e)
72         {
73             e.printStackTrace();
74         }
75         return null;
76     }
77 }       
Spring MVC實作檔案的上傳和下載下傳的功能

1.4建立視圖頁面

Spring MVC實作檔案的上傳和下載下傳的功能
1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
 2 <%
 3 String path = request.getContextPath();
 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 5 %>
 6 
 7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 8 <html>
 9   <head>
10     <base href="<%=basePath%>">
11     <title>upload</title>
12     <meta http-equiv="pragma" content="no-cache">
13     <meta http-equiv="cache-control" content="no-cache">
14     <meta http-equiv="expires" content="0">    
15     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
16     <meta http-equiv="description" content="This is my page">
17   </head>
18   
19   <body>
20     <form action="uploadFile.action" method="post" 
21         enctype="multipart/form-data">
22         <div>file<input name="cmf" type="file"/></div>
23         <div> <input type="submit" value="送出"/></div>
24     </form>
25     <hr/>
26     <a href="download.action">下載下傳</a>
27   </body>
28 </html>       
Spring MVC實作檔案的上傳和下載下傳的功能

結果:檔案上傳成功,但是重新部署項目(删除後重新部署)之後,上傳的檔案卻消失了!

經過查閱資料後發現:檔案上傳隻是上傳到了tomcat伺服器的webAPP下,并沒有上傳到工作空間中,是以重新部署後會丢失!但這種情況隻會出現在開發過程中,因為等到項目釋出成功後,就不會再重新部署項目了!是以此時我們可以在開發的過程中把檔案上傳的路徑傳到其他位置:如:String path = "D:/solution";

這樣,檔案就不會丢失了!