http://blog.darkthread.net/post-2007-09-05-kb-open-and-download-file-in-chinese-filename.aspx

※處理下載檔案,中文檔名的問題

→關鍵:Response.HeaderEncoding = System.Text.Encoding.GetEncoding("big5");

    Response.ContentType = "application/octet-stream";

    Response.HeaderEncoding =

        System.Text.Encoding.GetEncoding("big5");

    Response.AddHeader("content-disposition",

        "attachment;filename=中文檔名.xls");

    //實際上多會從DB讀取byte[]再BinaryWrite, 示範起見,

    //這裡用WriteFile混過去
    Response.WriteFile(Server.MapPath("中文檔名.xls"));

    Response.End();

 

KB-Open And Download File In Chinese Filename

網友帆問了一個好問題: 他提到用Response.AddHeader("content-disposition", "attachment;filename=" & HttpUtility.UrlEncode(filename))的方式指定下載檔名稱,會發生另存新檔(Save)時可存成中文檔名,但如果選擇開啟(Open),直接用Excel等程式開啟時,檔名會呈現%e4%b8...這種UrlEncode的形式。

這是一個好問題的原因是我也被它困擾很久了,最後選擇把頭埋進沙裡,告訴User不要上傳中文檔名的檔案找我麻煩。很巧,今天在MSDN Newsgroup上看到MVP小朱提示有個HeaderEncoding屬性

排版顯示純文字

protected void Page_Load(object sender, EventArgs e)
{
    Response.ContentType = "application/octet-stream";
    Response.HeaderEncoding = 
        System.Text.Encoding.GetEncoding("big5");
    Response.AddHeader("content-disposition", 
        "attachment;filename=中文檔名.xls");
    //實際上多會從DB讀取byte[]再BinaryWrite, 示範起見,
    //這裡用WriteFile混過去
    Response.WriteFile(Server.MapPath("中文檔名.xls"));
    Response.End();
}

原來HeaderEncoding是可以設定的,只要設成BIG5,就可以直接在Header中寫入中文字串,很簡單吧?但我測試的結果,HeaderEncoding設成UTF8會導致存檔或開啟都變成CAUZ97JK這種類似Temp的檔案名。那如果檔名有Unicode難字怎麼辦? 我目前打算繼續把頭再埋進沙裡,請User不要故意在檔名取難字煩我,變成問號的話自行負責。

另存與開啟都是中文檔名的感覺,爽!!

arrow
arrow
    全站熱搜

    weihsinchiu 發表在 痞客邦 留言(0) 人氣()