response實現文件的下載


 1 @Controller  
 2 public class FileController implements ServletContextAware{   
 3     //Spring這里是通過實現ServletContextAware接口來注入ServletContext對象   
 4     private ServletContext servletContext;   
 5   
 6   
 7     @RequestMapping("file/download")   
 8     public void fileDownload(HttpServletResponse response){   
 9         //獲取網站部署路徑(通過ServletContext對象),用於確定下載文件位置,從而實現下載   
10         String path = servletContext.getRealPath("/");   
11       response.rset();         //清楚空格等操作
12         //1.設置文件ContentType類型,這樣設置,會自動判斷下載文件類型   
13         response.setContentType("multipart/form-data");   
14         //2.設置文件頭:最后一個參數是設置下載文件名(假如我們叫a.pdf)   
15         response.setHeader("Content-Disposition", "attachment;fileName="+"a.pdf");   
16         ServletOutputStream out;   
17         //通過文件路徑獲得File對象(假如此路徑中有一個download.pdf文件)   
18         File file = new File(path + "download/" + "download.pdf");   
19   
20         try {   
21             FileInputStream inputStream = new FileInputStream(file);   
22   
23             //3.通過response獲取ServletOutputStream對象(out)   
24             out = response.getOutputStream();   
25   
26             int b = 0;   
27             byte[] buffer = new byte[512];   
28             while (b != -1){   
29                 b = inputStream.read(buffer);   
30                 //4.寫到輸出流(out)中   
31                 out.write(buffer,0,b);   
32             }   
33             inputStream.close();   
34             out.close();   
35             out.flush();   
36   
37         } catch (IOException e) {   
38             e.printStackTrace();   
39         }   
40     }   
41   
42     @Override  
43     public void setServletContext(ServletContext servletContext) {   
44         this.servletContext = servletContext;   
45     }   
46 }

 


免責聲明!

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



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