springMVC文件下载
1.1.1.?實現思路
1.讀取本地的文件
2.將讀取的文件顯示到頁面上
3.頁面點擊下載,下載文件
4.解決中文亂碼問題
?
1.1.2.?示例代碼
1.創建一個文件列表
| <%@?page?language="java"?contentType="text/html; charset=UTF-8" ????pageEncoding="UTF-8"%> <%@taglib?prefix="c"??uri="http://java.sun.com/jsp/jstl/core"%>???? <!DOCTYPE?html?PUBLIC?"-//W3C//DTD HTML 4.01 Transitional//EN"?"http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta?http-equiv="Content-Type"?content="text/html; charset=UTF-8"> <title>Insert title here</title> <script?type="text/javascript"> ??/* ????將路徑的參數編碼.發送到后臺方法在解碼 ??*/ ??function?download(val){ ??//將參數路徑編碼,Base64 ??var?filename=encodeURI(val); ??//escape防止瀏覽器轉義導致路徑編碼無法解釋 ??var?path="${pageContext.request.contextPath }/download.mvc?fname="+escape(filename); ??//跳轉到下載的路徑 ??window.location.href=path; ??} </script> </head> <body> 文件列表 <table?border="1"> ??<tr> ????<td>文件名</td> ????<td>下載</td> ??</tr> ??<c:forEach?var="fileName"?items="${fileNames }"> ??<tr> ????<td>${fileName}</td> ????<td><a?href="javascript:download('${fileName}')">下載</a></td> ??</tr> ??</c:forEach> </table> </body> </html> |
2.后臺代碼
| package?cn.lxm.controller; ? import?java.io.File; import?java.io.IOException; import?java.net.URLDecoder; import?java.util.Arrays; ? import?javax.servlet.http.HttpServletRequest; import?javax.servlet.http.HttpServletResponse; ? import?org.apache.commons.io.FileUtils; import?org.springframework.stereotype.Controller; import?org.springframework.web.bind.annotation.RequestMapping; ? @Controller public?class?DownloadController { /** ?* 文件下載首先要有一個下載列表 ?* @return ?*/ @RequestMapping(value="file-list") public?String listFile(HttpServletRequest request){ //1.讀取文件夾 d:\dir File dir?=new?File("d:/dir"); //2.獲得文件夾里面文件名 String[] fileNames?= dir.list(); System.out.println(Arrays.toString(fileNames)); //3.將文件名放在request request.setAttribute("fileNames", fileNames); return?"/file-list.jsp"; } ? /** ?* 文件下載 ?* 所謂的文件下載就是將文件寫入到HttpServletResponse里面 ?*/ @RequestMapping(value="download") public?void?download(String fname,HttpServletResponse response){ try?{ //解碼 fname=URLDecoder.decode(fname, "UTF-8"); System.out.println(fname+"-----"); //1.通過文件名獲得文件 File file=new?File("d:/dir/"+fname); //將文件變成流,寫入到HttpServletResponse的輸出流里面 //使用commons-io-2.2.jar的文件處理類實現,將文件轉成一個byte[]字節流 ?byte[] array=null; ? array?= FileUtils.readFileToByteArray(file); //在response輸出之前,設置輸出的格式 //默認不支持中文,new String(fname.getBytes(),"ISO-8859-1"),轉義中文編碼 response.addHeader("Content-Disposition", "attachment;filename="+new?String(fname.getBytes(),"ISO-8859-1")); //將文件寫入到response的輸出流 response.getOutputStream().write(array); } catch?(IOException e) { // TODO?Auto-generated catch block e.printStackTrace(); } } } |
轉載于:https://www.cnblogs.com/bky-lxm/p/10747608.html
總結
以上是生活随笔為你收集整理的springMVC文件下载的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 远程视频技术
- 下一篇: JS 设计模式四 -- 模块模式