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();
    }
  • 相关阅读:
    20201226 ZooKeeper
    20201220 分布式理论、架构设计(自定义RPC)
    20201217 Cluster模式潜在问题及解决方案、Web服务综合解决方案
    20201216 Nginx
    20201214 Tomcat
    20201209 Spring Boot
    20201206 Spring Data JPA
    20201205 Spring MVC
    20201128 IoC容器设计实现及Spring源码分析
    numpy数组及处理:效率对比
  • 原文地址:https://www.cnblogs.com/masonblog/p/8628637.html
Copyright © 2011-2022 走看看