zoukankan      html  css  js  c++  java
  • 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();
    }
  • 相关阅读:
    java第二周的学习知识
    java第一次课
    今天晚上有事,代码假期完成。
    [leetcode] Minimum Path Sum
    java访问权限整理
    java IO整理-File
    java初始化顺序
    enum使用整理
    工厂模式总结
    java IO-流
  • 原文地址:https://www.cnblogs.com/masonblog/p/8628637.html
Copyright © 2011-2022 走看看