在上網的過程中,經常會發現點擊一個按鈕或者鏈接之後,出現文件的保存。這就是服務器向你發送文件。在工作中也遇到了這樣的問題。這裏簡單的總結一下。
實現文件下載最簡單的方法就是在網頁上做超級鏈接,如<a href="xxxxx/xxxx.jpg">點擊下載</a>。
(1) 這樣會把服務器上的目錄資源暴露給用戶。(主要)
(2) 每當修改服務器上的文件位置的時候,都需要對應修改。當然你可以使用jsp等動態網頁的方法。
還可以通過發送請求,服務器返回文件的方法來實現。
可採用:1. RequestDispatcher的方式;2.文件流輸出的方式下載。
需要設置的屬性有 content-type, content-disposition。
其中,Content-disposition 是 MIME 協議的擴展,MIME 協議指示 MIME 用戶代理如何顯示附加的文件。當 Internet Explorer 接收到頭時,它會激活文件下載對話框,它的文件名框自動填充了頭中指定的文件名。(請注意,這是設計導致的;無法使用此功能將文檔保存到用戶的計算機上,而不向用戶詢問保存位置。)
服務端向客戶端遊覽器發送文件時,如果是瀏覽器支持的文件類型,一般會默認使用瀏覽器打開,比如txt、jpg等,會直接在瀏覽器中顯示,如果需要提示用戶保存,就要利用Content-Disposition進行一下處理,關鍵在於一定要加上attachment:
Response.AppendHeader("Content-Disposition","attachment;filename=FileName.txt");
備註:這樣瀏覽器會提示保存還是打開,即使選擇打開,也會使用相關聯的程序比如記事本打開,而不是IE直接打開了。
例子1RequestDispatcher的方式
public static void fileDownloadDispatcher(HttpServletRequest request, HttpServletResponse response) throws Exception {
String filePath = "/fileName";// 即將下載的文件的相對路徑
String fileDisplay = URLEncoder.encode("fileDisplay", "UTF-8");// 下載文件時顯示的文件保存名稱
response.setContentType("application/x-download");// 設置爲下載application/x-download
response.addHeader("Content-Disposition", "attachment;filename=" + fileDisplay);
try {
RequestDispatcher dis = request.getRequestDispatcher(filePath);
if (dis != null) {
dis.forward(request, response);
}
response.flushBuffer();
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}
例子2文件流輸出的方式
public static void fileDownloadStream(HttpServletRequest request, HttpServletResponse response) throws IOException {
String filePath = "/fileName";// 即將下載的文件的相對路徑
String fileDisplay = URLEncoder.encode("fileDisplay", "UTF-8");// 下載文件時顯示的文件保存名稱
response.reset();
response.setContentType("application/x-download");
response.setCharacterEncoding("UTF-8");
response.setHeader("Content-Disposition", "attachment;filename=\"" + fileDisplay + "\"");
OutputStream responseStream = response.getOutputStream();
InputStream fis = new FileInputStream(filePath);
DataInputStream dis = new DataInputStream(fis);
byte[] buffer = new byte[1024 * 10];
int n = 0;
try {
while ((n = fis.read(buffer)) != -1) {
responseStream.write(buffer, 0, n);
responseStream.flush();
}
} catch (IOException e) {
} finally {
if (responseStream != null) {
responseStream.flush();
responseStream.close();
}
if (dis != null) {
dis.close();
}
}
}
參考
http://www.cnblogs.com/brucejia/archive/2012/12/24/2831060.html
http://blog.csdn.net/bripengandre/article/details/2192982
http://blog.csdn.net/cs_ghy/article/details/8142354