header中Content-Disposition的作用與使用方法


1 Content-disposition的含義

是 MIME 協議的擴展,MIME 協議指示 MIME 用戶代理如何顯示附加的文件。Content-disposition其實可以控制用戶請求所得的內容存為一個文件的時候提供一個默認的文件名,文件直接在瀏覽器上顯示或者在訪問時彈出文件下載對話框。

格式說明:
content-disposition = "Content-Disposition" ":" disposition-type *( ";" disposition-parm )  

字段說明:

Content-Disposition屬性有兩種類型:inline 和 attachment

inline :將文件內容直接顯示在頁面

attachment:彈出對話框讓用戶下載:disposition-type是以什么方式下載,如attachment為以附件方式下載

disposition-parm為默認保存時的文件名
服務端向客戶端游覽器發送文件時,如果是瀏覽器支持的文件類型,一般會默認使用瀏覽器打開,比如txt、jpg等,會直接在瀏覽器中顯示,如果需要提示用戶保存,就要利用Content-Disposition進行一下處理,關鍵在於一定要加上

Response.AppendHeader("Content-Disposition","attachment;filename=FileName.txt");

2 代碼示例

File file = new File("rfc1806.txt");  
String filename = file.getName();  
response.setHeader("Content-Type","text/plain");  
response.addHeader("Content-Disposition","inline;filename=" + new String(filename.getBytes(),"utf-8"));  
response.addHeader("Content-Length","" + file.length());  

3 下載文件名亂碼解決方案

if (isIE) {
//IE瀏覽器的亂碼問題解決
    fileName = URLEncoder.encode(fileName, "UTF-8");
} else {
    //萬能亂碼問題解決
    fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
}
response.setHeader("Content-disposition", "attachment;filename=\"" + fileName + "\"");
//剩下的就是將文件流輸出到response
//FileCopyUtils.copy(inputStream, response.getOutputStream);

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM