1、通過HttpServletResponse對象實現文件下載
服務端向客戶端游覽器發送文件時,如果是瀏覽器支持的文件類型,一般會默認使用瀏覽器打開,比如txt、jpg等,會直接在瀏覽器中顯示,如果需要提示用戶保存,就要利用Content-Disposition進行一下處理,關鍵在於一定要加上attachment:
Response.AppendHeader("Content-Disposition","attachment;filename=FileName.txt");
// 1.獲取要下載的文件的絕對路徑 String realPath = this.getServletContext().getRealPath("/download/泉州行政區圖0.jpg"); System.out.println(realPath); // 2.獲取要下載的文件名 String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1); // 3.設置content-disposition響應頭控制瀏覽器彈出保存框,若沒有此句則瀏覽器會直接打開並顯示文件。中文名要經過URLEncoder.encode編碼,否則雖然客戶端能下載但顯示的名字是亂碼 response.setHeader("content-disposition", "attachment;filename=hehe" + URLEncoder.encode(fileName, "UTF-8")); // 4.獲取要下載的文件輸入流 InputStream in = new FileInputStream(realPath); int len = 0; // 5.創建數據緩沖區 byte[] buffer = new byte[1024]; // 6.通過response對象獲取OutputStream流 OutputStream out = response.getOutputStream(); // 7.將FileInputStream流寫入到buffer緩沖區 while ((len = in.read(buffer)) > 0) { // 8.使用OutputStream將緩沖區的數據輸出到客戶端瀏覽器 out.write(buffer, 0, len); } in.close();
詳情見參考資料:http://www.cnblogs.com/brucejia/archive/2012/12/24/2831060.html
2、關於Content-disposition
Content-disposition 是 MIME 協議的擴展,MIME 協議指示 MIME 用戶代理如何顯示附加的文件。當 Internet Explorer 接收到頭時,它會激活文件下載對話框,它的文件名框自動填充了頭中指定的文件名。
關於Content-disposition可參考http://www.cnblogs.com/brucejia/archive/2012/12/24/2831060.html