標籤:style blog http color java 使用 os strong
【本文簡介】
一個servlet 檔案下載 的簡單例子。
【檔案夾結構】
【java代碼】
1 package com.zjm.www.servlet; 2 3 import java.io.BufferedInputStream; 4 import java.io.BufferedOutputStream; 5 import java.io.File; 6 import java.io.FileInputStream; 7 import java.io.IOException; 8 import java.io.InputStream; 9 import java.io.OutputStream;10 11 import javax.servlet.ServletException;12 import javax.servlet.http.HttpServlet;13 import javax.servlet.http.HttpServletRequest;14 import javax.servlet.http.HttpServletResponse;15 16 /**17 * @描述 servlet 檔案下載18 * @作者 小M19 * @部落格 http://www.cnblogs.com/xiaoMzjm/20 * @時間 2014/07/3021 */22 public class DownLoadServlet extends HttpServlet {23 24 25 private static final long serialVersionUID = 1L;26 27 public void doGet(HttpServletRequest request, HttpServletResponse response)28 throws ServletException, IOException {29 doPost(request,response);30 }31 32 public void doPost(HttpServletRequest request, HttpServletResponse response)33 throws ServletException, IOException {34 35 // 轉碼,建議使用過濾器過濾。36 request.setCharacterEncoding("UTF8");37 response.setCharacterEncoding("UTF8");38 39 // 擷取上傳檔案的 檔案名稱40 String fileName = request.getParameter("fileName");41 42 // 檔案所放的檔案夾,伺服器檔案相對路徑。有關路徑問題,請參考另一篇博文:http://www.cnblogs.com/xiaoMzjm/p/3878758.html43 String path = request.getServletContext().getRealPath("/")+"\\DownLoadFile\\";44 45 // 下載路徑 = 檔案所放的檔案夾 + 檔案名稱46 String downLoadPath = path + fileName;47 48 // 建立輸入資料流 串連檔案,並把檔案 讀 到流中49 File file = new File(downLoadPath);50 InputStream fis = new BufferedInputStream(new FileInputStream(file));51 52 // 判斷檔案有有多少位元組可以讀53 byte[] buffer = new byte[fis.available()];54 fis.read(buffer);55 fis.close();56 57 // 清空response58 response.reset();59 60 /**61 * 設定response的Header,必須設。62 * 【幾個標頭檔簡介】:63 * 1、Content-disposition是MIME協議的擴充,此協議可讓瀏覽器彈出下載框。同時可以改變下載時檔案的檔案名稱。64 * 2、Content-Length用於描述HTTP訊息實體的傳輸長度。65 * 在HTTP協議中,訊息實體長度和訊息實體的傳輸長度是有區別,比如說gzip壓縮下,訊息實體長度是壓縮前的長度,訊息實體的傳輸長度是gzip壓縮後的長度。66 */67 response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("utf-8"),"ISO-8859-1"));68 response.addHeader("Content-Length", "" + file.length());69 OutputStream out = new BufferedOutputStream(response.getOutputStream());70 71 /**72 * 配置MIME類型,通知瀏覽器下載的檔案的格式。73 * 更多 MIME類型 和 尾碼名 的映射可在百度文庫搜尋 : “MIME類型大全” 或者戳中串連:74 * http://wenku.baidu.com/link?url=SIJffXFE68HnvhI39h0c0PtjSzz7v8SoYzo274HcEx8jYRm-V07_WkotLQdVnT_JGyNhIUY_bjQRgnfz_b53rg5EnHD_ist84Pq-uWMYjyG75 */76 response.setContentType("application/octet-stream");77 78 // 輸出79 out.write(buffer);80 out.flush();81 out.close();82 }83 }