首页 > 代码库 > SpringMVC文件上传下载

SpringMVC文件上传下载

在Spring MVC的基础框架搭建起来后,我们测试了spring mvc中的返回值类型,如果你还没有搭建好springmvc的架构请参考博文->http://www.cnblogs.com/qixiaoyizhan/p/5819392.html

今天我们来讲讲spring mvc中的文件上传和下载的几种方法。

首先附上文件目录->我们需要配置的我做了记号->

技术分享

 

一、文件上传


首先为了方便后续的操作,以及精简代码,我们在Utils包下封装一个文件上传下载的帮助类: Files_Helper_DG

技术分享

 1 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:qixiao14  * Time:2016年9月2日23:47:5115  */16 public final class Files_Helper_DG {17     /**18      * 私有构造方法,限制该类不能被实例化19      */20     private Files_Helper_DG() {21         throw new Error("The class Cannot be instance !");22     }23 24     /**25      * spring mvc files Upload method (transferTo method)26      * spring mvc 中的文件上传方法 trasferTo 的方式上传,参数为MultipartFile27      *28      * @param request       HttpServletRequest29      * @param multipartFile MultipartFile(spring)30      * @param filePath      filePath example "/files/Upload"31      * @return32      */33     public static String FilesUpload_transferTo_spring(HttpServletRequest request, MultipartFile multipartFile, String filePath) {34         //get Date path35         String DatePath = new SimpleDateFormat("yyyyMMdd").format(new Date());36         //get server path (real path)37         String savePath = request.getSession().getServletContext().getRealPath(filePath) + File.separator + DatePath;38         // if dir not exists , mkdir39         System.out.println(savePath);40         File saveDir = new File(savePath);41         if (!saveDir.exists() || !saveDir.isDirectory()) {42             //create dir43             saveDir.mkdir();44         }45         if (multipartFile != null) {46             //get files suffix47             String suffix = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."));48             //use UUID get uuid string49             String uuidName = UUID.randomUUID().toString() + suffix;// make new file name50             //filePath+fileName the complex file Name51             String fileName = savePath + File.separator + uuidName;52             //return relative Path53             String relativePath = filePath + File.separator + DatePath + File.separator + uuidName;54             try {55                 //save file56                 multipartFile.transferTo(new File(fileName));57                 //return relative Path58                 return relativePath;59             } catch (IOException e) {60                 e.printStackTrace();61                 return null;62             }63         } else64             return null;65     }66 67     /**68      * @param request  HttpServletRequest69      * @param response HttpServletResponse70      * @param filePath example "/filesOut/Download/mst.txt"71      * @return72      */73     public static void FilesDownload_servlet(HttpServletRequest request, HttpServletResponse response, String filePath) {74         //get server path (real path)75         String realPath = request.getSession().getServletContext().getRealPath(filePath);76         File file = new File(realPath);77         String filenames = file.getName();78         InputStream inputStream;79         try {80             inputStream = new BufferedInputStream(new FileInputStream(file));81             byte[] buffer = new byte[inputStream.available()];82             inputStream.read(buffer);83             inputStream.close();84             response.reset();85             // 先去掉文件名称中的空格,然后转换编码格式为utf-8,保证不出现乱码,这个文件名称用于浏览器的下载框中自动显示的文件名86             response.addHeader("Content-Disposition", "attachment;filename=" + new String(filenames.replaceAll(" ", "").getBytes("utf-8"), "iso8859-1"));87             response.addHeader("Content-Length", "" + file.length());88             OutputStream os = new BufferedOutputStream(response.getOutputStream());89             response.setContentType("application/octet-stream");90             os.write(buffer);// 输出文件91             os.flush();92             os.close();93         } catch (Exception e) {94             e.printStackTrace();95         }96     }97 }

 然后我们新建一个控制器类 FileUploadController

技术分享

首先我们先展示出全部的代码,然后我们进行分步说明--->

技术分享
  1 package HelloSpringMVC.controller;  2   3   4 import Utils.Files_Helper_DG;  5 import org.apache.commons.fileupload.FileItem;  6 import org.apache.commons.fileupload.disk.DiskFileItemFactory;  7 import org.apache.commons.fileupload.servlet.ServletFileUpload;  8 import org.springframework.stereotype.Controller;  9 import org.springframework.web.bind.annotation.RequestMapping; 10 import org.springframework.web.bind.annotation.RequestParam; 11 import org.springframework.web.bind.annotation.ResponseBody; 12 import org.springframework.web.multipart.MultipartFile; 13 import org.springframework.web.multipart.MultipartHttpServletRequest; 14 import org.springframework.web.multipart.commons.CommonsMultipartResolver; 15  16 import javax.servlet.http.HttpServletRequest; 17 import javax.servlet.http.HttpServletResponse; 18 import java.io.*; 19 import java.util.Iterator; 20 import java.util.List; 21  22 /** 23  * Created by qixiao on 2016/8/30. 24  */ 25 @Controller 26 @RequestMapping(value = "http://www.mamicode.com/FileUpload/*") 27 public class FileUploadController { 28  29     /* 30      * 方式一 31      * 采用 fileUpload_multipartFile , file.transferTo 来保存上传的文件 32      */ 33     @RequestMapping(value = "http://www.mamicode.com/fileUpload_multipartFile") 34     @ResponseBody 35     public String fileUpload_multipartFile(HttpServletRequest request, @RequestParam("file_upload") MultipartFile multipartFile) { 36         //调用保存文件的帮助类进行保存文件,并返回文件的相对路径 37         String filePath = Files_Helper_DG.FilesUpload_transferTo_spring(request, multipartFile, "/filesOut/Upload"); 38         return "{\"TFMark\":\"true\",\"Msg\":\"upload success !\",\"filePath\":\"" + filePath + "\"}"; 39     } 40  41     /* 42      * 方式二 43      * 采用 fileUpload_multipartRequest file.transferTo 来保存上传文件 44      * 参数不写 MultipartFile multipartFile 在request请求里面直接转成multipartRequest,从multipartRequest中获取到文件流 45      */ 46     @RequestMapping(value = "http://www.mamicode.com/fileUpload_multipartRequest") 47     @ResponseBody 48     public String fileUpload_multipartRequest(HttpServletRequest request) { 49         //将request转成MultipartHttpServletRequest 50         MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; 51         //页面控件的文件流,对应页面控件 input file_upload 52         MultipartFile multipartFile = multipartRequest.getFile("file_upload"); 53         //调用保存文件的帮助类进行保存文件,并返回文件的相对路径 54         String filePath = Files_Helper_DG.FilesUpload_transferTo_spring(request, multipartFile, "/filesOut/Upload"); 55         return "{\"TFMark\":\"true\",\"Msg\":\"upload success !\",\"filePath\":\"" + filePath + "\"}"; 56     } 57  58     /* 59      * 方式三 60      * 采用 CommonsMultipartResolver file.transferTo 来保存上传文件 61      * 自动扫描全部的input表单 62      */ 63     @RequestMapping(value = "http://www.mamicode.com/fileUpload_CommonsMultipartResolver") 64     @ResponseBody 65     public String fileUpload_CommonsMultipartResolver(HttpServletRequest request) { 66         //将当前上下文初始化给  CommonsMultipartResolver (多部分解析器) 67         CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext()); 68         //检查form中是否有enctype="multipart/form-data" 69         if (multipartResolver.isMultipart(request)) { 70             //将request变成多部分request 71             MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; 72             //获取multiRequest 中所有的文件名 73             Iterator iter = multipartRequest.getFileNames(); 74             while (iter.hasNext()) { 75                 //一次遍历所有文件 76                 MultipartFile multipartFile = multipartRequest.getFile(iter.next().toString()); 77                 //调用保存文件的帮助类进行保存文件,并返回文件的相对路径 78                 String fileName = Files_Helper_DG.FilesUpload_transferTo_spring(request, multipartFile, "/filesOut/Upload"); 79                 System.out.println(fileName); 80             } 81         } 82         return "upload success ! "; 83     } 84  85     /* 86      * 方式四 87      * 通过流的方式上传文件 88      * @RequestParam("file") 将name=file控件得到的文件封装成CommonsMultipartFile 对象 89      */ 90     @RequestMapping(value = "http://www.mamicode.com/fileUpload_stream") 91     @ResponseBody 92     public String fileUpload_stream(HttpServletRequest request) { 93         //得到上传文件的保存目录,将上传的文件存放于WEB-INF目录下,不允许外界直接访问,保证上传文件的安全 94         String savePath = request.getSession().getServletContext().getRealPath("/filesOut/Upload"); 95         File file = new File(savePath); 96         //判断上传文件的保存目录是否存在 97         if (!file.exists() && !file.isDirectory()) { 98             //创建目录 99             file.mkdir();100         }101         try {102             //使用Apache文件上传组件处理文件上传步骤:103             //1、创建一个DiskFileItemFactory工厂104             DiskFileItemFactory factory = new DiskFileItemFactory();105             //2、创建一个文件上传解析器106             ServletFileUpload upload = new ServletFileUpload(factory);107             //解决上传文件名的中文乱码108             upload.setHeaderEncoding("UTF-8");109             //3、判断提交上来的数据是否是上传表单的数据110             if (!ServletFileUpload.isMultipartContent(request)) {111                 //按照传统方式获取数据112                 return "is not form upload data ";113             }114             //4、使用ServletFileUpload解析器解析上传数据,解析结果返回的是一个List<FileItem>集合,每一个FileItem对应一个Form表单的输入项115             List<FileItem> list = upload.parseRequest(request);116             System.out.println("start---------");117             System.out.println(list);118             for (FileItem item : list) {119                 System.out.println("begin ----");120                 //如果fileitem中封装的是普通输入项的数据121                 if (item.isFormField()) {122                     String name = item.getFieldName();123                     //解决普通输入项的数据的中文乱码问题124                     String value = http://www.mamicode.com/item.getString("UTF-8");125                     //value = http://www.mamicode.com/new String(value.getBytes("iso8859-1"),"UTF-8");126                     System.out.println(name + "=" + value);127                 } else {//如果fileitem中封装的是上传文件128                     //得到上传的文件名称,129                     String filename = item.getName();130                     System.out.println(filename);131                     if (filename == null || filename.trim().equals("")) {132                         continue;133                     }134                     //注意:不同的浏览器提交的文件名是不一样的,有些浏览器提交上来的文件名是带有路径的,如:  c:\a\b\1.txt,而有些只是单纯的文件名,如:1.txt135                     //处理获取到的上传文件的文件名的路径部分,只保留文件名部分136                     String suffix = item.getName().substring(item.getName().lastIndexOf("."));137                     //获取item中的上传文件的输入流138                     InputStream in = item.getInputStream();139                     //创建一个文件输出流140                     FileOutputStream out = new FileOutputStream(savePath + "/123" + suffix);141                     //创建一个缓冲区142                     byte buffer[] = new byte[1024];143                     //判断输入流中的数据是否已经读完的标识144                     int len = 0;145                     //循环将输入流读入到缓冲区当中,(len=in.read(buffer))>0就表示in里面还有数据146                     while ((len = in.read(buffer)) > 0) {147                         //使用FileOutputStream输出流将缓冲区的数据写入到指定的目录(savePath + "\\" + filename)当中148                         out.write(buffer, 0, len);149                     }150                     //关闭输入流151                     in.close();152                     //关闭输出流153                     out.close();154                     //删除处理文件上传时生成的临时文件155                     item.delete();156                 }157             }158             return "upload success !";159         } catch (Exception e) {160             e.printStackTrace();161         }162         return "upload fail";163     }164 165     /*166      * 多文件上传167      * 采用 MultipartFile[] multipartFile 上传文件方法168      */169     @RequestMapping(value = "http://www.mamicode.com/fileUpload_spring_list")170     @ResponseBody171     public String fileUpload_spring_list(HttpServletRequest request, @RequestParam("file_upload") MultipartFile[] multipartFile) {172         //判断file数组不能为空并且长度大于0173         if (multipartFile != null && multipartFile.length > 0) {174             //循环获取file数组中得文件175             try {176                 for (int i = 0; i < multipartFile.length; i++) {177                     MultipartFile file = multipartFile[i];178                     //保存文件179                     String fileName = Files_Helper_DG.FilesUpload_transferTo_spring(request, file, "/filesOut/Upload");180                     System.out.println(fileName);181                 }182                 return "{\"TFMark\":\"true\",\"Msg\":\"upload success !\"}";183             } catch (Exception ee) {184                 return "{\"TFMark\":\"false\",\"Msg\":\"参数传递有误!\"}";185             }186         }187         return "{\"TFMark\":\"false\",\"Msg\":\"参数传递有误!\"}";188     }189 190     /**191      * 文件下载192      *193      * @param response194      */195     @RequestMapping(value = "http://www.mamicode.com/fileDownload_servlet")196     public void fileDownload_servlet(HttpServletRequest request, HttpServletResponse response) {197         Files_Helper_DG.FilesDownload_servlet(request,response,"/filesOut/Download/mst.txt");198     }199 }
FileUploadController

 方式一:采用 fileUpload_multipartFile , file.transferTo 来保存上传的文件

 1 /* 2      * 方式一 3      * 采用 fileUpload_multipartFile , file.transferTo 来保存上传的文件 4      */ 5     @RequestMapping(value = "http://www.mamicode.com/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 = "http://www.mamicode.com/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 = "http://www.mamicode.com/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     }

方式四:通过流的方式上传文件(这种方法和servlet里面上传文件的方法类似,但本人这种方法存在上传文件损坏的问题,希望大神们能帮本人解决,感激不尽!~~~)

 1  @RequestMapping(value = "http://www.mamicode.com/fileUpload_stream") 2     @ResponseBody 3     public String fileUpload_stream(HttpServletRequest request) { 4         //得到上传文件的保存目录,将上传的文件存放于WEB-INF目录下,不允许外界直接访问,保证上传文件的安全 5         String savePath = request.getSession().getServletContext().getRealPath("/filesOut/Upload"); 6         File file = new File(savePath); 7         //判断上传文件的保存目录是否存在 8         if (!file.exists() && !file.isDirectory()) { 9             //创建目录10             file.mkdir();11         }12         try {13             //使用Apache文件上传组件处理文件上传步骤:14             //1、创建一个DiskFileItemFactory工厂15             DiskFileItemFactory factory = new DiskFileItemFactory();16             //2、创建一个文件上传解析器17             ServletFileUpload upload = new ServletFileUpload(factory);18             //解决上传文件名的中文乱码19             upload.setHeaderEncoding("UTF-8");20             //3、判断提交上来的数据是否是上传表单的数据21             if (!ServletFileUpload.isMultipartContent(request)) {22                 //按照传统方式获取数据23                 return "is not form upload data ";24             }25             //4、使用ServletFileUpload解析器解析上传数据,解析结果返回的是一个List<FileItem>集合,每一个FileItem对应一个Form表单的输入项26             List<FileItem> list = upload.parseRequest(request);27             System.out.println("start---------");28             System.out.println(list);29             for (FileItem item : list) {30                 System.out.println("begin ----");31                 //如果fileitem中封装的是普通输入项的数据32                 if (item.isFormField()) {33                     String name = item.getFieldName();34                     //解决普通输入项的数据的中文乱码问题35                     String value = http://www.mamicode.com/item.getString("UTF-8");36                     //value = http://www.mamicode.com/new String(value.getBytes("iso8859-1"),"UTF-8");37                     System.out.println(name + "=" + value);38                 } else {//如果fileitem中封装的是上传文件39                     //得到上传的文件名称,40                     String filename = item.getName();41                     System.out.println(filename);42                     if (filename == null || filename.trim().equals("")) {43                         continue;44                     }45                     //注意:不同的浏览器提交的文件名是不一样的,有些浏览器提交上来的文件名是带有路径的,如:  c:\a\b\1.txt,而有些只是单纯的文件名,如:1.txt46                     //处理获取到的上传文件的文件名的路径部分,只保留文件名部分47                     String suffix = item.getName().substring(item.getName().lastIndexOf("."));48                     //获取item中的上传文件的输入流49                     InputStream in = item.getInputStream();50                     //创建一个文件输出流51                     FileOutputStream out = new FileOutputStream(savePath + "/123" + suffix);52                     //创建一个缓冲区53                     byte buffer[] = new byte[1024];54                     //判断输入流中的数据是否已经读完的标识55                     int len = 0;56                     //循环将输入流读入到缓冲区当中,(len=in.read(buffer))>0就表示in里面还有数据57                     while ((len = in.read(buffer)) > 0) {58                         //使用FileOutputStream输出流将缓冲区的数据写入到指定的目录(savePath + "\\" + filename)当中59                         out.write(buffer, 0, len);60                     }61                     //关闭输入流62                     in.close();63                     //关闭输出流64                     out.close();65                     //删除处理文件上传时生成的临时文件66                     item.delete();67                 }68             }69             return "upload success !";70         } catch (Exception e) {71             e.printStackTrace();72         }73         return "upload fail";74     }
多文件上传(其实是将上面的 MultipartFile 写成数组形式)
 1 @RequestMapping(value = "http://www.mamicode.com/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下新建文件夹目录/filesOut/Upload,并且新建一个/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 </head>11 <body>12 <h3>文件上传</h3><br>13 14 <h3>采用 fileUpload_multipartFile , file.transferTo 来保存上传的文件</h3>15 <form name="form1" action="/FileUpload/fileUpload_multipartFile" method="post" enctype="multipart/form-data">16     <input type="file" name="file_upload">17     <input type="submit" value="upload"/>18 </form>19 <hr>20 21 <h3>采用 fileUpload_multipartRequest file.transferTo 来保存上传文件</h3>22 <form name="form2" action="/FileUpload/fileUpload_multipartRequest" method="post" enctype="multipart/form-data">23     <input type="file" name="file_upload">24     <input type="submit" value="upload"/>25 </form>26 <hr>27 28 <h3>采用 CommonsMultipartResolver file.transferTo 来保存上传文件</h3>29 <form name="form3" action="/FileUpload/fileUpload_CommonsMultipartResolver" method="post" enctype="multipart/form-data">30     <input type="file" name="file_upload">31     <input type="submit" value="upload"/>32 </form>33 <hr>34 35 <h3>使通过流的方式上传文件--存在上传后无法使用的问题</h3>36 <form name="form4" action="/FileUpload/fileUpload_stream" method="post" enctype="multipart/form-data">37     <input type="file" name="file_upload">38     <input type="submit" value="upload"/>39 </form>40 <hr>41 42 <h3>多文件上传 采用 MultipartFile[] multipartFile 上传文件方法</h3>43 <form name="form5" action="/FileUpload/fileUpload_spring_list" method="post" enctype="multipart/form-data">44     <input type="file" name="file_upload">45     <input type="file" name="file_upload">46     <input type="file" name="file_upload">47     <input type="submit" value="upload"/>48 </form>49 <hr>50 51 <h3>通过 a 标签的方式进行文件下载</h3><br>52 <a href="<%=basePath%>filesOut/Download/mst.txt">通过 a 标签下载文件 mst.txt</a>53 <hr>54 <h3>通过 Response 文件流的方式下载文件</h3>55 <a href="/FileUpload/fileDownload_servlet">通过 文件流 的方式下载文件 mst.txt</a>56 57 </body>58 </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.xsd10 http://www.springframework.org/schema/mvc11 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="/filesOut/" mapping="/filesOut/**" />29     <mvc:resources location="/scripts/" mapping="/scripts/**" />30     <mvc:resources location="/styles/" mapping="/styles/**" />31     <mvc:resources location="/Views/" mapping="/Views/**" />32 33     <!-- 多部分文件上传 -->34     <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">35         <property name="maxUploadSize" value="104857600" />36         <property name="maxInMemorySize" value="4096" />37         <property name="defaultEncoding" value="UTF-8"></property>38     </bean>39 </beans>

然后我们运行tomcat进入http://localhost:8080/Views/FileUpload/FileUpload.jsp

打开后,页面如下:

技术分享

我们依次选择文件->

技术分享

然后依次点击upload按钮,进行文件的上传->

技术分享

技术分享

 

技术分享

 

技术分享

技术分享

可见,5种上传都已经执行成功!下面我们打开文件目录查看一下上传的文件->

技术分享

细心的同志们会发现使用流上传的并没有成功,这种方式仍然存在bug待调试,有成功的记得联系我哦~

那么我们其他的方式执行已经都成功了!

 

 

二、文件下载


 在控制器类 FileUploadController里面继续添加代码->

1 @RequestMapping(value = "http://www.mamicode.com/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");

 然后我们进行测试->

前面我们新建的文件夹/filesOut/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/ 且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。

 

SpringMVC文件上传下载