通知瀏覽器下載文件,而不是直接打開下載


 1 // 1.獲取要下載的文件的絕對路徑
 2         String realPath = this.getServletContext().getRealPath("/download/泉州行政區圖0.jpg");
 3         System.out.println(realPath);
 4         // 2.獲取要下載的文件名
 5         String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1);
 6         // 3.設置content-disposition響應頭控制瀏覽器彈出保存框,若沒有此句則瀏覽器會直接打開並顯示文件。中文名要經過URLEncoder.encode編碼,否則雖然客戶端能下載但顯示的名字是亂碼
 7         response.setHeader("content-disposition", "attachment;filename=hehe" + URLEncoder.encode(fileName, "UTF-8"));
 8         // 4.獲取要下載的文件輸入流
 9         InputStream in = new FileInputStream(realPath);
10         int len = 0;
11         // 5.創建數據緩沖區
12         byte[] buffer = new byte[1024];
13         // 6.通過response對象獲取OutputStream流
14         OutputStream out = response.getOutputStream();
15         // 7.將FileInputStream流寫入到buffer緩沖區
16         while ((len = in.read(buffer)) > 0) {
17             // 8.使用OutputStream將緩沖區的數據輸出到客戶端瀏覽器
18             out.write(buffer, 0, len);
19         }
20     }

此代碼未經測試,只是轉載分享http://www.cnblogs.com/z-sm/p/5467048.html


免責聲明!

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



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