2013年5月6日 星期一

下載檔案中文檔名變亂碼


問題:

下載檔案中文檔名變亂碼。

解決方法:

範例程式:
string fileName = "全國縣市統計報表";
Response.HeaderEncoding = System.Text.Encoding.GetEncoding("big5");
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + ".xls");
Response.ContentType = "application/vnd.ms-excel";

討論:

Mozilla Firefox 、 Google Chrome 瀏覽器下,不會有編碼的問題,但在 IE 的版本中中文檔案名稱會變成亂碼, IE 對於 Content-Disposition 是用 ANSI 編碼,碰到你用 Unicode 編碼的檔名解析就會錯誤,造成亂碼[1]。
因此將目前標頭輸出資料流的編碼方式改為 BIG5 。

有人提出在 HttpHandler 中設定 context.Response.HeaderEncoding 無效的問題,可以參考保哥[4][5]的方法。


範例程式:
string fileName = "檢測資料";
if (Request.Browser.Browser == "IE")
{
    fileName = Server.UrlPathEncode(fileName);
}

Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + ".xls");
Response.ContentType = "application/vnd.ms-excel";


參考文獻:
1.           [CodeIgniter] 解決 CI 下載函式 force_download 碰到 IE 下載中文檔名變亂碼
2.           KB-Open And Download File In Chinese Filename
3.           HttpResponse.HeaderEncoding 屬性
4.           在 HttpHandler 中設定 context.Response.HeaderEncoding 無效的問題
5.           ASP.NET 如何設定強制下載檔案並正確處理中文檔名的問題

0 意見:

張貼留言