1. 程式人生 > >HttpServletResponse實現檔案的下載

HttpServletResponse實現檔案的下載

private void downloadFileByOutputStream(HttpServletResponse response)
32             throws FileNotFoundException, IOException {
33         //1.獲取要下載的檔案的絕對路徑
34         String realPath = this.getServletContext().getRealPath("/download/1.JPG");
35         //2.獲取要下載的檔名
36         String fileName = realPath.substring(realPath.lastIndexOf("\\"
)+1); 37 //3.設定content-disposition響應頭控制瀏覽器以下載的形式開啟檔案 38 response.setHeader("content-disposition", "attachment;filename="+fileName); 39 //4.獲取要下載的檔案輸入流 40 InputStream in = new FileInputStream(realPath); 41 int len = 0; 42 //5.建立資料緩衝區 43 byte[] buffer = new
byte[1024]; 44 //6.通過response物件獲取OutputStream流 45 OutputStream out = response.getOutputStream(); 46 //7.將FileInputStream流寫入到buffer緩衝區 47 while ((len = in.read(buffer)) > 0) { 48 //8.使用OutputStream將緩衝區的資料輸出到客戶端瀏覽器 49 out.write(buffer,0,len); 50 } 51
in.close(); 52 }