1 // 1.獲取要下載的文件的絕對路徑 2 String realPath = this.getServletContext().getRealPath("/download/泉州行政區(qū)圖0.jpg"); 3 System.out.println(realPath); 4 // 2.獲取要下載的文件名 5 String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1); 6 // 3.設(shè)置content-disposition響應(yīng)頭控制瀏覽器彈出保存框,若沒有此句則瀏覽器會直接打開并顯示文件。中文名要經(jīng)過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.創(chuàng)建數(shù)據(jù)緩沖區(qū)12 byte[] buffer = new byte[1024];13 // 6.通過response對象獲取OutputStream流14 OutputStream out = response.getOutputStream();15 // 7.將FileInputStream流寫入到buffer緩沖區(qū)16 while ((len = in.read(buffer)) > 0) {17 // 8.使用OutputStream將緩沖區(qū)的數(shù)據(jù)輸出到客戶端瀏覽器18 out.write(buffer, 0, len);19 }20 }
此代碼未經(jīng)測試,只是轉(zhuǎn)載分享http://www.cnblogs.com/z-sm/p/5467048.html