SpringMVC實現從磁盤中下載文件


除了文件的上傳我們還需要從磁盤下載

實現文件的下載只要編寫一個控制器,完成讀寫操作和響應頭和數據類型的設置就可以了

下面演示的是從G盤imgs文件夾中下載文件

具體代碼如下

 1 package com.cqupt.dayday;
 2 
 3 import org.springframework.stereotype.Controller;
 4 import org.springframework.web.bind.annotation.RequestMapping;
 5 
 6 import javax.servlet.http.HttpServletRequest;
 7 import javax.servlet.http.HttpServletResponse;
 8 import java.io.*;
 9 
10 /**
11  * Created by I am master on 2017/5/16.
12  */
13 @Controller
14 public class ResourceController {
15     @RequestMapping("/download")
16     public String download(String fileName, HttpServletRequest request, HttpServletResponse response) throws IOException {
17         response.setCharacterEncoding("utf-8");
18         //返回的數據類型
19         response.setContentType("application/pdf");
20         //響應頭
21         response.setHeader("Content-Disposition", "attachment;fileName="
22                 + fileName);
23         InputStream inputStream=null;
24         OutputStream outputStream=null;
25         //路徑
26         String path ="G:"+ File.separator+"imgs"+File.separator;
27         byte[] bytes = new byte[2048];
28         try {
29             File file=new File(path,fileName);
30             inputStream = new FileInputStream(file);
31             outputStream = response.getOutputStream();
32             int length;
33             //inputStream.read(bytes)從file中讀取數據,-1是讀取完的標志
34             while ((length = inputStream.read(bytes)) > 0) {
35                 //寫數據
36                 outputStream.write(bytes, 0, length);
37             }
38         } catch (FileNotFoundException e) {
39             e.printStackTrace();
40         } catch (IOException e) {
41             e.printStackTrace();
42         }finally {
43             //關閉輸入輸出流
44             if(outputStream!=null) {
45                 outputStream.close();
46             }
47             if(inputStream!=null) {
48                 inputStream.close();
49             }
50         }
51         return null;
52     }
53 }

用了注解進行描述就不在重復了

在寫的過程中遇到的問題:FileNotFoundException

原因:路徑不正確

一定要注意路徑問題在寫的時候

前端代碼:

 1 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
 2 <html>
 3 <head>
 4     <title>Title</title>
 5 </head>
 6 <body>
 7       <center><h1>Download Page</h1></center>
 8       <a href="download?fileName=B.pdf">B.pdf</a>
 9  </body>
10 </html>

 

測試頁面:

點擊即完成下載

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM