SpringMVC文件上傳下載

在Spring MVC的基礎框架搭建起來後,咱們測試了spring mvc中的返回值類型,若是你尚未搭建好springmvc的架構請參考博文->http://www.cnblogs.com/qixiaoyizhan/p/5819392.htmljavascript

今天咱們來說講spring mvc中的文件上傳和下載的幾種方法。css

首先附上文件目錄->咱們須要配置的我作了記號->html

 

1、文件上傳java


首先爲了方便後續的操做,以及精簡代碼,咱們在Utils包下封裝一個文件上傳下載的幫助類:Files_Helper_DGjquery

 Files_Helper_DG 代碼web

package Utils;
  2 
  3 import org.springframework.web.multipart.MultipartFile;
  4 
  5 import javax.servlet.http.HttpServletRequest;
  6 import javax.servlet.http.HttpServletResponse;
  7 import java.io.*;
  8 import java.text.SimpleDateFormat;
  9 import java.util.Date;
 10 import java.util.UUID;
 11 
 12 /**
 13  * Author:qixiao
 14  * Time:2016-9-2 23:47:51
 15  */
 16 public final class Files_Utils_DG {
 17     /**
 18      * private constructor method that make class can not be instantiation
 19      */
 20     private Files_Utils_DG() {
 21         throw new Error("The class Cannot be instance !");
 22     }
 23 
 24     /**
 25      * spring mvc files Upload method (transferTo method)
 26      * MultipartFile use TransferTo method upload
 27      *
 28      * @param request       HttpServletRequest
 29      * @param multipartFile MultipartFile(spring)
 30      * @param filePath      filePath example "/files/Upload"
 31      * @return
 32      */
 33     public static String FilesUpload_transferTo_spring(HttpServletRequest request, MultipartFile multipartFile, String filePath) {
 34         if (multipartFile != null) {
 35             //get files suffix
 36             String suffix = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."));
 37             //filePath+fileName the complex file Name
 38             String absolutePath = getAndSetAbsolutePath(request, filePath, suffix);
 39             //return relative Path
 40             String relativePath = getRelativePath(filePath, suffix);
 41             try {
 42                 //save file
 43                 multipartFile.transferTo(new File(absolutePath));
 44                 //return relative Path
 45                 return relativePath;
 46             } catch (IOException e) {
 47                 e.printStackTrace();
 48                 return null;
 49             }
 50         } else
 51             return null;
 52     }
 53 
 54     /**
 55      * user stream type save files
 56      * @param request       HttpServletRequest
 57      * @param multipartFile MultipartFile  support CommonsMultipartFile file
 58      * @param filePath      filePath example "/files/Upload"
 59      * @return
 60      */
 61     public static String FilesUpload_stream(HttpServletRequest request,MultipartFile multipartFile,String filePath) {
 62         if (multipartFile != null) {
 63             //get files suffix
 64             String suffix = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."));
 65             //filePath+fileName the complex file Name
 66             String absolutePath = getAndSetAbsolutePath(request, filePath, suffix);
 67             //return relative Path
 68             String relativePath = getRelativePath(filePath, suffix);
 69             try{
 70                 InputStream inputStream = multipartFile.getInputStream();
 71                 FileOutputStream fileOutputStream = new FileOutputStream(absolutePath);
 72                 byte buffer[] = new byte[4096]; //create a buffer
 73                 long fileSize = multipartFile.getSize();
 74                 if(fileSize<=buffer.length){//if fileSize < buffer
 75                     buffer = new byte[(int)fileSize];
 76                 }
 77                 int line =0;
 78                 while((line = inputStream.read(buffer)) >0 )
 79                 {
 80                     fileOutputStream.write(buffer,0,line);
 81                 }
 82                 fileOutputStream.close();
 83                 inputStream.close();
 84                 return relativePath;
 85             }catch (Exception e){
 86                 e.printStackTrace();
 87             }
 88         } else
 89             return null;
 90         return null;
 91     }
 92 
 93     /**
 94      * @param request  HttpServletRequest
 95      * @param response HttpServletResponse
 96      * @param filePath example "/filesOut/Download/mst.txt"
 97      * @return
 98      */
 99     public static void FilesDownload_stream(HttpServletRequest request, HttpServletResponse response, String filePath) {
100         //get server path (real path)
101         String realPath = request.getSession().getServletContext().getRealPath(filePath);
102         File file = new File(realPath);
103         String filenames = file.getName();
104         InputStream inputStream;
105         try {
106             inputStream = new BufferedInputStream(new FileInputStream(file));
107             byte[] buffer = new byte[inputStream.available()];
108             inputStream.read(buffer);
109             inputStream.close();
110             response.reset();
111             // 先去掉文件名稱中的空格,而後轉換編碼格式爲utf-8,保證不出現亂碼,這個文件名稱用於瀏覽器的下載框中自動顯示的文件名
112             response.addHeader("Content-Disposition", "attachment;filename=" + new String(filenames.replaceAll(" ", "").getBytes("utf-8"), "iso8859-1"));
113             response.addHeader("Content-Length", "" + file.length());
114             OutputStream os = new BufferedOutputStream(response.getOutputStream());
115             response.setContentType("application/octet-stream");
116             os.write(buffer);// 輸出文件
117             os.flush();
118             os.close();
119         } catch (Exception e) {
120             e.printStackTrace();
121         }
122     }
123 
124 
125     //-------------------------------------------------------------------------------
126     //return server absolute path(real path)
127     public static String getServerPath(HttpServletRequest request, String filePath) {
128         return request.getSession().getServletContext().getRealPath(filePath);
129     }
130 
131     //return a dir that named date of today ; example:20160912
132     public static String getDataPath() {
133         return new SimpleDateFormat("yyyyMMdd").format(new Date());
134     }
135 
136     //check if the path has exist if not create it
137     public static void checkDir(String savePath) {
138         File dir = new File(savePath);
139         if (!dir.exists() || !dir.isDirectory()) {
140             dir.mkdir();
141         }
142     }
143 
144     //return an UUID Name parameter (suffix cover '.') example: ".jpg"、".txt"
145     public static String getUUIDName(String suffix) {
146         return UUID.randomUUID().toString() + suffix;// make new file name
147     }
148 
149     //return server absolute path(real path) the style is  「server absolute path/DataPath/UUIDName」filePath example "/files/Upload"
150     public static String getAndSetAbsolutePath(HttpServletRequest request, String filePath, String suffix) {
151         String savePath = getServerPath(request, filePath) + File.separator + getDataPath() + File.separator;//example:F:/qixiao/files/Upload/20160912/
152         checkDir(savePath);//check if the path has exist if not create it
153         return savePath + getUUIDName(suffix);
154     }
155 
156     //get the relative path of files style is 「/filePath/DataPath/UUIDName」filePath example "/files/Upload"
157     public static String getRelativePath(String filePath, String suffix) {
158         return filePath + File.separator + getDataPath() + File.separator + getUUIDName(suffix);//example:/files/Upload/20160912/
159     }
160 }

而後咱們新建一個控制器類 FileUploadControllerajax

首先咱們先展現出所有的代碼,而後咱們進行分步說明--->spring

1 package HelloSpringMVC.controller;
  2 
  3 
  4 import Utils.Files_Utils_DG;
  5 import org.springframework.stereotype.Controller;
  6 import org.springframework.web.bind.annotation.RequestMapping;
  7 import org.springframework.web.bind.annotation.RequestMethod;
  8 import org.springframework.web.bind.annotation.RequestParam;
  9 import org.springframework.web.bind.annotation.ResponseBody;
 10 import org.springframework.web.multipart.MultipartFile;
 11 import org.springframework.web.multipart.MultipartHttpServletRequest;
 12 import org.springframework.web.multipart.commons.CommonsMultipartResolver;
 13 
 14 import javax.servlet.http.HttpServletRequest;
 15 import javax.servlet.http.HttpServletResponse;
 16 import java.util.Iterator;
 17 
 18 /**
 19  * Created by qixiao on 2016/8/30.
 20  */
 21 @Controller
 22 @RequestMapping(value = "/FileUpload/*")
 23 public class FileUploadController {
 24 
 25     /*
 26      * 方式一
 27      * 採用 fileUpload_multipartFile , file.transferTo 來保存上傳的文件
 28      */
 29     @RequestMapping(value = "fileUpload_multipartFile")
 30     @ResponseBody
 31     public String fileUpload_multipartFile(HttpServletRequest request, @RequestParam("file_upload") MultipartFile multipartFile) {
 32         //調用保存文件的幫助類進行保存文件,並返回文件的相對路徑
 33         String filePath = Files_Utils_DG.FilesUpload_transferTo_spring(request, multipartFile, "/files/upload");
 34         return "{'TFMark':'true','Msg':'upload success !','filePath':'" + filePath + "'}";
 35     }
 36 
 37     /*
 38      * 方式二
 39      * 採用 fileUpload_multipartRequest file.transferTo 來保存上傳文件
 40      * 參數不寫 MultipartFile multipartFile 在request請求裏面直接轉成multipartRequest,從multipartRequest中獲取到文件流
 41      */
 42     @RequestMapping(value = "fileUpload_multipartRequest")
 43     @ResponseBody
 44     public String fileUpload_multipartRequest(HttpServletRequest request) {
 45         //將request轉成MultipartHttpServletRequest
 46         MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
 47         //頁面控件的文件流,對應頁面控件 input file_upload
 48         MultipartFile multipartFile = multipartRequest.getFile("file_upload");
 49         //調用保存文件的幫助類進行保存文件,並返回文件的相對路徑
 50         String filePath = Files_Utils_DG.FilesUpload_transferTo_spring(request, multipartFile, "/files/upload");
 51         return "{'TFMark':'true','Msg':'upload success !','filePath':'" + filePath + "'}";
 52     }
 53 
 54     /*
 55      * 方式三
 56      * 採用 CommonsMultipartResolver file.transferTo 來保存上傳文件
 57      * 自動掃描所有的input表單
 58      */
 59     @RequestMapping(value = "fileUpload_CommonsMultipartResolver")
 60     @ResponseBody
 61     public String fileUpload_CommonsMultipartResolver(HttpServletRequest request) {
 62         //將當前上下文初始化給  CommonsMultipartResolver (多部分解析器)
 63         CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
 64         //檢查form中是否有enctype="multipart/form-data"
 65         if (multipartResolver.isMultipart(request)) {
 66             //將request變成多部分request
 67             MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
 68             //獲取multiRequest 中全部的文件名
 69             Iterator iter = multipartRequest.getFileNames();
 70             while (iter.hasNext()) {
 71                 //一次遍歷全部文件
 72                 MultipartFile multipartFile = multipartRequest.getFile(iter.next().toString());
 73                 //調用保存文件的幫助類進行保存文件,並返回文件的相對路徑
 74                 String fileName = Files_Utils_DG.FilesUpload_transferTo_spring(request, multipartFile, "/files/upload");
 75                 System.out.println(fileName);
 76             }
 77         }
 78         return "upload success ! ";
 79     }
 80 
 81     /*
 82      * 方式四
 83      * 經過流的方式上傳文件
 84      */
 85     @RequestMapping("fileUpload_stream")
 86     @ResponseBody
 87     public String upFile(HttpServletRequest request, @RequestParam("file_upload") MultipartFile multipartFile){
 88         String filePath= Files_Utils_DG.FilesUpload_stream(request,multipartFile,"/files/upload");
 89         return "{'TFMark':'true','Msg':'upload success !','filePath':'" + filePath + "'}";
 90     }
 91 
 92     /*
 93      * 方式五
 94      * 採用 fileUpload_ajax , file.transferTo 來保存上傳的文件 異步
 95      */
 96     @RequestMapping(value = "fileUpload_ajax",method = RequestMethod.POST,produces = {"application/json;charset=UTF-8"})
 97     @ResponseBody
 98     public String fileUpload_ajax(HttpServletRequest request, @RequestParam("file_AjaxFile") MultipartFile  multipartFile) {
 99         //調用保存文件的幫助類進行保存文件,並返回文件的相對路徑
100         String filePath = Files_Utils_DG.FilesUpload_transferTo_spring(request, multipartFile, "/files/upload");
101         return "{'TFMark':'true','Msg':'upload success !','filePath':'" + filePath + "'}";
102     }
103 
104     /*
105      * 多文件上傳
106      * 採用 MultipartFile[] multipartFile 上傳文件方法
107      */
108     @RequestMapping(value = "fileUpload_spring_list")
109     @ResponseBody
110     public String fileUpload_spring_list(HttpServletRequest request, @RequestParam("file_upload") MultipartFile[] multipartFile) {
111         //判斷file數組不能爲空而且長度大於0
112         if (multipartFile != null && multipartFile.length > 0) {
113             //循環獲取file數組中得文件
114             try {
115                 for (int i = 0; i < multipartFile.length; i++) {
116                     MultipartFile file = multipartFile[i];
117                     //保存文件
118                     String fileName = Files_Utils_DG.FilesUpload_transferTo_spring(request, file, "/files/upload");
119                     System.out.println(fileName);
120                 }
121                 return "{'TFMark':'true','Msg':'upload success !'}";
122             } catch (Exception ee) {
123                 return "{'TFMark':'false','Msg':'參數傳遞有誤!'}";
124             }
125         }
126         return "{'TFMark':'false','Msg':'參數傳遞有誤!'}";
127     }
128 
129     /**
130      * 文件下載
131      *
132      * @param response
133      */
134     @RequestMapping(value = "fileDownload_servlet")
135     public void fileDownload_servlet(HttpServletRequest request, HttpServletResponse response) {
136         Files_Utils_DG.FilesDownload_stream(request,response,"/files/download/mst.txt");
137     }
138 }
複製代碼
 

 方式一:採用 fileUpload_multipartFile , file.transferTo 來保存上傳的文件

複製代碼
 1 /*
 2      * 方式一
 3      * 採用 fileUpload_multipartFile , file.transferTo 來保存上傳的文件
 4      */
 5     @RequestMapping(value = "fileUpload_multipartFile")
 6     @ResponseBody
 7     public String fileUpload_multipartFile(HttpServletRequest request, @RequestParam("file_upload") MultipartFile multipartFile) {
 8         //調用保存文件的幫助類進行保存文件,並返回文件的相對路徑
 9         String filePath = Files_Helper_DG.FilesUpload_transferTo_spring(request, multipartFile, "/filesOut/Upload");
10         return "{\"TFMark\":\"true\",\"Msg\":\"upload success !\",\"filePath\":\"" + filePath + "\"}";
11     }
複製代碼
方式二:採用 fileUpload_multipartRequest file.transferTo 來保存上傳文件

複製代碼
 1  @RequestMapping(value = "fileUpload_multipartRequest")
 2     @ResponseBody
 3     public String fileUpload_multipartRequest(HttpServletRequest request) {
 4         //將request轉成MultipartHttpServletRequest
 5         MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
 6         //頁面控件的文件流,對應頁面控件 input file_upload
 7         MultipartFile multipartFile = multipartRequest.getFile("file_upload");
 8         //調用保存文件的幫助類進行保存文件,並返回文件的相對路徑
 9         String filePath = Files_Helper_DG.FilesUpload_transferTo_spring(request, multipartFile, "/filesOut/Upload");
10         return "{\"TFMark\":\"true\",\"Msg\":\"upload success !\",\"filePath\":\"" + filePath + "\"}";
11     }
複製代碼
 方式三:採用 CommonsMultipartResolver file.transferTo 來保存上傳文件---自動掃描所有的input表單

複製代碼
 1  @RequestMapping(value = "fileUpload_CommonsMultipartResolver")
 2     @ResponseBody
 3     public String fileUpload_CommonsMultipartResolver(HttpServletRequest request) {
 4         //將當前上下文初始化給  CommonsMultipartResolver (多部分解析器)
 5         CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
 6         //檢查form中是否有enctype="multipart/form-data"
 7         if (multipartResolver.isMultipart(request)) {
 8             //將request變成多部分request
 9             MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
10             //獲取multiRequest 中全部的文件名
11             Iterator iter = multipartRequest.getFileNames();
12             while (iter.hasNext()) {
13                 //一次遍歷全部文件
14                 MultipartFile multipartFile = multipartRequest.getFile(iter.next().toString());
15                 //調用保存文件的幫助類進行保存文件,並返回文件的相對路徑
16                 String fileName = Files_Helper_DG.FilesUpload_transferTo_spring(request, multipartFile, "/filesOut/Upload");
17                 System.out.println(fileName);
18             }
19         }
20         return "upload success ! ";
21     }

方式四:經過流的方式上傳文件json

1 @RequestMapping("fileUpload_stream")
2     @ResponseBody
3     public String upFile(HttpServletRequest request, @RequestParam("file_upload") MultipartFile multipartFile){
4         String filePath=Files_Helper_DG.FilesUpload_stream(request,multipartFile,"/filesOut/Upload");
5         return "{\"TFMark\":\"true\",\"Msg\":\"upload success !\",\"filePath\":\"" + filePath + "\"}";
6     }

方式五:採用ajaxFileUpload.js插件與異步上傳的方式上傳文件數組

1 @RequestMapping(value = "fileUpload_ajax",method = RequestMethod.POST,produces = {"application/json;charset=UTF-8"})
2     @ResponseBody
3     public String fileUpload_ajax(HttpServletRequest request, @RequestParam("file_AjaxFile") MultipartFile  multipartFile) {
4         //調用保存文件的幫助類進行保存文件,並返回文件的相對路徑
5         String filePath = Files_Utils_DG.FilesUpload_transferTo_spring(request, multipartFile, "/files/upload");
6         return "{'TFMark':'true','Msg':'upload success !','filePath':'" + filePath + "'}";
7     }

 上述方法須要 ajaxfileupload.js 插件的支持,該插件

多文件上傳(實際上是將上面的 MultipartFile 寫成數組形式)
 1 @RequestMapping(value = "fileUpload_spring_list")
 2     @ResponseBody
 3     public String fileUpload_spring_list(HttpServletRequest request, @RequestParam("file_upload") MultipartFile[] multipartFile) {
 4         //判斷file數組不能爲空而且長度大於0
 5         if (multipartFile != null && multipartFile.length > 0) {
 6             //循環獲取file數組中得文件
 7             try {
 8                 for (int i = 0; i < multipartFile.length; i++) {
 9                     MultipartFile file = multipartFile[i];
10                     //保存文件
11                     String fileName = Files_Helper_DG.FilesUpload_transferTo_spring(request, file, "/filesOut/Upload");
12                     System.out.println(fileName);
13                 }
14                 return "{\"TFMark\":\"true\",\"Msg\":\"upload success !\"}";
15             } catch (Exception ee) {
16                 return "{\"TFMark\":\"false\",\"Msg\":\"參數傳遞有誤!\"}";
17             }
18         }
19         return "{\"TFMark\":\"false\",\"Msg\":\"參數傳遞有誤!\"}";
20     }

 

下面咱們進行測試:

首先在webapp下新建文件夾目錄/files/download,而且新建一個/Views/FileUpload/FileUpload.jsp

 

注意文件目錄結構以及目錄層次!!!

FileUpload.jsp代碼以下

複製代碼
  1 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
  2 <%
  3     String path = request.getContextPath();
  4     String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
  5 %>
  6 <html>
  7 <head>
  8     <base href="<%=basePath%>">
  9     <title>fileUpload</title>
 10     <script src="<%=basePath%>scripts/jquery-1.11.1.js"></script>
 11     <script src="<%=basePath%>scripts/ajaxfileupload.js"></script>
 12 </head>
 13 <body>
 14 <h3>文件上傳</h3><br>
 15 
 16 <h3>採用 fileUpload_multipartFile , file.transferTo 來保存上傳的文件</h3>
 17 <form name="form1" action="/FileUpload/fileUpload_multipartFile" method="post" enctype="multipart/form-data">
 18     <input type="file" name="file_upload">
 19     <input type="submit" value="upload"/>
 20 </form>
 21 <hr>
 22 
 23 <h3>採用 fileUpload_multipartRequest file.transferTo 來保存上傳文件</h3>
 24 <form name="form2" action="/FileUpload/fileUpload_multipartRequest" method="post" enctype="multipart/form-data">
 25     <input type="file" name="file_upload">
 26     <input type="submit" value="upload"/>
 27 </form>
 28 <hr>
 29 
 30 <h3>採用 CommonsMultipartResolver file.transferTo 來保存上傳文件</h3>
 31 <form name="form3" action="/FileUpload/fileUpload_CommonsMultipartResolver" method="post" enctype="multipart/form-data">
 32     <input type="file" name="file_upload">
 33     <input type="submit" value="upload"/>
 34 </form>
 35 <hr>
 36 
 37 <h3>經過流的方式上傳文件</h3>
 38 <form name="form4" action="/FileUpload/fileUpload_stream" method="post" enctype="multipart/form-data">
 39     <input type="file" name="file_upload">
 40     <input type="submit" value="upload"/>
 41 </form>
 42 <hr>
 43 
 44 <h3>經過ajax插件 ajaxfileupload.js 來異步上傳文件</h3>
 45 <form name="form5" action="/" method="post" enctype="multipart/form-data">
 46     <input type="file" id="file_AjaxFile" name="file_AjaxFile">
 47     <input type="button" value="upload" onclick="fileUploadAjax()"/><span id="sp_AjaxFile"></span><br><br>
 48     上傳進度:<span id="sp_fileUploadProgress">0%</span>
 49 </form>
 50 <script type="text/javascript">
 51     function fileUploadAjax() {
 52         if ($("#file_AjaxFile").val().length > 0) {
 53             progressInterval=setInterval(getProgress,500);
 54             $.ajaxFileUpload({
 55                 url: '/FileUpload/fileUpload_ajax', //用於文件上傳的服務器端請求地址
 56                 type: "post",
 57                 secureuri: false, //通常設置爲false
 58                 fileElementId: 'file_AjaxFile', //文件上傳空間的id屬性  <input type="file" id="file1" name="file" />
 59                 dataType: 'application/json', //返回值類型 通常設置爲json
 60                 success: function (data)  //服務器成功響應處理函數
 61                 {
 62                     var jsonObject = eval('(' + data + ')');
 63                     $("#sp_AjaxFile").html(" Upload Success ! filePath:" + jsonObject.filePath);
 64                 },
 65                 error: function (data, status, e)//服務器響應失敗處理函數
 66                 {
 67                     alert(e);
 68                 }
 69             });//end ajaxfile
 70         }
 71         else {
 72             alert("請選擇文件!");
 73         }
 74     }
 75     var progressInterval = null;
 76     var i=0;
 77     var getProgress=function (){
 78         $.get("/FileUpload/fileUploadprogress",
 79                 {},
 80         function (data) {
 81             $("#sp_fileUploadProgress").html(i+++data);
 82             if(data==100||i==100)
 83                 clearInterval(progressInterval);
 84         }
 85     );
 86     }
 87 </script>
 88 <hr>
 89 
 90 <h3>多文件上傳 採用 MultipartFile[] multipartFile 上傳文件方法</h3>
 91 <form name="form5" action="/FileUpload/fileUpload_spring_list" method="post" enctype="multipart/form-data">
 92     <input type="file" name="file_upload">
 93     <input type="file" name="file_upload">
 94     <input type="file" name="file_upload">
 95     <input type="submit" value="upload"/>
 96 </form>
 97 <hr>
 98 
 99 <h3>經過 a 標籤的方式進行文件下載</h3><br>
100 <a href="<%=basePath%>filesOut/Download/mst.txt">經過 a 標籤下載文件 mst.txt</a>
101 <hr>
102 <h3>經過 Response 文件流的方式下載文件</h3>
103 <a href="/FileUpload/fileDownload_servlet">經過 文件流 的方式下載文件 mst.txt</a>
104 
105 </body>
106 </html>
複製代碼

 

這裏必定要記得在spring-servlet.xml裏面配置訪問靜態路徑方法->下面我附上spring-servlet.xml

複製代碼
 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4        xmlns:context="http://www.springframework.org/schema/context"
 5        xmlns:mvc="http://www.springframework.org/schema/mvc"
 6        xsi:schemaLocation="http://www.springframework.org/schema/beans
 7 http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
 8 http://www.springframework.org/schema/context
 9 http://www.springframework.org/schema/context/spring-context-3.1.xsd
10 http://www.springframework.org/schema/mvc
11 http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">
12 
13     <!-- 啓動註解驅動的Spring MVC功能,註冊請求url和註解POJO類方法的映射-->  
14     <mvc:annotation-driven >
15          
16     </mvc:annotation-driven>
17    
18     <!-- 啓動包掃描功能,以便註冊帶有@Controller、@service、@repository、@Component等註解的類成爲spring的bean -->
19     <context:component-scan base-package="HelloSpringMVC.controller" />
20     <!-- 對模型視圖名稱的解析,在請求時模型視圖名稱添加先後綴 -->
21      <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
22          <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
23          <property name="prefix" value="/"/>    <!-- 前綴 -->
24          <property name="suffix" value=".jsp"/>    <!-- 後綴 -->
25      </bean>
26     <!-- 訪問靜態文件(jpg,js,css)的方法 -->
27     <mvc:resources location="/files/" mapping="/files/**" />
28     <mvc:resources location="/scripts/" mapping="/scripts/**" />
29     <mvc:resources location="/styles/" mapping="/styles/**" />
30     <mvc:resources location="/Views/" mapping="/Views/**" />
31 
32     <!-- 多部分文件上傳 需配置MultipartResolver處理器-->
33     <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
34         <property name="maxUploadSize" value="104857600" />
35         <property name="maxInMemorySize" value="4096" />
36         <property name="defaultEncoding" value="UTF-8"></property>
37     </bean>
38     <!-- SpringMVC在超出上傳文件限制時,會拋出org.springframework.web.multipart.MaxUploadSizeExceededException -->
39     <!-- 該異常是SpringMVC在檢查上傳的文件信息時拋出來的,並且此時尚未進入到Controller方法中 -->
40     <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
41         <property name="exceptionMappings">
42             <props>
43                 <!-- 遇到MaxUploadSizeExceededException異常時,自動跳轉到/WEB-INF/jsp/error_fileupload.jsp頁面 -->
44                 <prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">error_fileupload</prop>
45             </props>
46         </property>
47     </bean>
48 </beans>
複製代碼

 

而後咱們運行tomcat進入http://localhost:8080/Views/FileUpload/FileUpload.jsp

打開後,頁面以下:

 

咱們依次選擇文件->

 

共八個文件!

而後依次點擊upload按鈕,進行文件的上傳->

 

可見,六種上傳都已經執行成功!下面咱們打開文件目錄查看一下上傳的文件->

一共八個文件!證實全部文件都上傳成功了!

2、文件下載


 在控制器類 FileUploadController裏面繼續添加代碼->

1 @RequestMapping(value = "fileDownload_servlet")
2     public void fileDownload_servlet(HttpServletRequest request, HttpServletResponse response) {
3         Files_Helper_DG.FilesDownload_servlet(request,response,"/filesOut/Download/mst.txt");
4     }

這裏調用了幫助類 Files_Helper_DG.FilesDownload_servlet(request,response,"/filesOut/Download/mst.txt");

 而後咱們進行測試->

前面咱們新建的文件夾/files/download,在裏面放一個文件mst.txt,代碼訪問的就是這個文件!

而後是咱們FileUpload.jsp,前面已經拷貝過了這段代碼->

1 <h3>經過 a 標籤的方式進行文件下載</h3><br>
2 <a href="<%=basePath%>filesOut/Download/mst.txt">經過 a 標籤下載文件 mst.txt</a>
3 <hr>
4 <h3>經過 Response 文件流的方式下載文件</h3>
5 <a href="/FileUpload/fileDownload_servlet">經過 文件流 的方式下載文件 mst.txt</a>

首先是第一種直接訪問文件目錄,此方式有缺陷,暴露了項目文件結構,形成安全隱患!

點擊即可下載!(若是瀏覽器能夠讀取文件,則會直接瀏覽器打開,咱們能夠右鍵->連接另存爲選擇路徑保存)

而後咱們點擊第二種下載方式->實際項目中,咱們應該優先選擇第二種方式,提升了安全性!

從服務器直接下載到瀏覽器默認的保存文件目錄!(本人在F:)

 

 到此,咱們的 spring mvc 文件上傳下載已經實現!


 

本文爲七小站主原創做品,轉載請註明出處:http://www.cnblogs.com/qixiaoyizhan/ 且在文章頁面明顯位置給出原文連接,不然保留追究法律責任的權利。

另外安利一個博主的我的網站http://qixiao123.cn/ 歡迎你們訪問!

相關文章
相關標籤/搜索