1. 下載概述
- 下載就是向客戶端響應字節數據! 將一個文件變成字節數組, 使用
response.getOutputStream()
來響應給瀏覽器!!
2. 下載要求
- 兩個頭一個流
Content-Type: 傳遞給客戶端的文件的 MIME 類型;
可以使用文件名稱調用 ServletContext 的 getMimeType() 方法, 得到 MIME 類型!Content-Disposition:attachment;filename=xxx:
它的默認值為 inline, 表示在瀏覽器窗口中打開! attachment 表示附件, filname 后面跟隨的是顯示在
下載框中的文件名稱!- 流:要下載的文件數據!
3. 具體代碼
// 下載
public class DownloadServlet extends HttpServlet{
public void doGet(HttpServletRequest request, HttpServletResponse resp)
throws ServletException,IOException{
String filename = "F:浮誇.mp3";
//根據文件名獲取 MIME 類型
String contentType = this.getServletContext().getMimeType(filename);
String contentDisposition = "attachment;filename=a.mp3";
// 輸入流
FileInputStream input = new FileInputStream(filename);
// 設置頭
resp.setHeader("Content-Type",contentType);
resp.setHeader("Content-Disposition",contentDisposition);
// 獲取綁定了客戶端的流
ServletOutputStream output = resp.getOutputStream();
// 把輸入流中的數據寫入到輸出流中
IOUtils.copy(input,output);
input.close();
}
}
4. 下載文件編碼問題
- 顯示在下載框中為中文名稱時,會出現亂碼
- FireFox: Base64 編碼;
- 其他大部分瀏覽器: URL 編碼.
- 通用方案:
filename = new String(filename.getBytes("GBK"),"ISO-88859-1");
參考資料:
