web項目中使用火狐瀏覽器導出文件時文件名亂碼


原因

主要是編碼的問題。
在設置文件名稱前,加上判斷。
判斷下載者使用的瀏覽器,
如果不是火狐瀏覽器,則對文件名稱進行UTF8編碼;
如果是火狐瀏覽器,則不對文件名稱進行操作.

解決辦法

文件名稱編碼時進行判斷,不是火狐瀏覽器時才進行編碼。

if (HttpContext.Current.Request.ServerVariables["http_user_agent"].ToLower().IndexOf("firefox") == -1) {   }

/// <summary>
/// 下載文件
/// </summary>
/// <param name="s_path"></param>
public static void downloadfile(string sFilePath)
{
    System.IO.FileInfo file = new System.IO.FileInfo(sFilePath);
    string sFileName = file.Name;
    //如果不是或火狐瀏覽器,則對文件名稱進行UTF8編碼
    if (HttpContext.Current.Request.ServerVariables["http_user_agent"].ToLower().IndexOf("firefox") == -1)
    {
        sFileName = System.Web.HttpUtility.UrlEncode(file.Name, System.Text.Encoding.UTF8);
    }
    HttpContext.Current.Response.ContentType = "application/ms-download";
    HttpContext.Current.Response.Clear();
    HttpContext.Current.Response.AddHeader("Content-Type", "application/octet-stream");
    HttpContext.Current.Response.Charset = "utf-8";
    HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + sFileName);
    HttpContext.Current.Response.AddHeader("Content-Length", file.Length.ToString());
    HttpContext.Current.Response.WriteFile(file.FullName);
    HttpContext.Current.Response.Flush();
    HttpContext.Current.Response.Clear();
    //此句注釋,如果執行了此代碼,則整個執行結束(不會執行下載文件方法后面的代碼)
    //HttpContext.Current.Response.End();
}

 


免責聲明!

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



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