The Will Will Web 記載著 Will 在網路世界的學習心得與技術分享 ASP.NET 如何設定強制下載檔案並正確處理中文檔名的問題

The Will Will Web – All posts tagged ‘utf-8’

我想一般人的作法都是透過設定 HTTP 回應 Content-Disposition 標頭(Header)的方式告知用戶端(Browser)強制下載檔案的,例如:

string fileName = “ExportData.csv";

string strContentDisposition = String.Format(“{0}; filename=\"{1}\"", “attachment", fileName);

Response.AddHeader(“Content-Disposition", strContentDisposition);

透過上述程式碼,就可以讓 Browser 強制下載此頁的內容,也就是該頁的內容(可能是文件或二進位檔案)不會直接在瀏覽器中開啟或下載後直接開啟相關程式(如:Office)。

其中 Content-Disposition 標頭的第一組參數是 attachment,代表此頁唯一個「附件檔」,如果你將 attchment 改成 inline 的話,就代表這是一個內嵌與其他網頁內檔案(如:圖檔、CSS、JavaScript、Flash、…),而這也是「預設」的設定,所以也就等於不加上 Content-Disposition 標頭的情況。

而 Content-Disposition 標頭的第二組參數是 filename,也就是你可以指定下載檔案時預設的儲存檔名,在此範例中的下載檔名是 ExportData.csv (如下圖示)

發表迴響

你的電子郵件位址並不會被公開。 必要欄位標記為 *

What is 4 + 10 ?
Please leave these two fields as-is:
IMPORTANT! To be able to proceed, you need to solve the following simple math (so we know that you are a human) :-)