前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >在ASP.NET中,IE与Firefox下载文件带汉字名时乱码的解决方法

在ASP.NET中,IE与Firefox下载文件带汉字名时乱码的解决方法

作者头像
跟着阿笨一起玩NET
发布2018-09-19 15:13:32
1.2K0
发布2018-09-19 15:13:32
举报
文章被收录于专栏:跟着阿笨一起玩NET

解决办法:

代码语言:javascript
复制
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
HttpContext.Current.Response.Charset = "gb2312";
HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xls", string.IsNullOrEmpty(fileName) ? DateTime.Now.ToString("yyyyMMddHHmmssfff") : System.Web.HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8)));
HttpContext.Current.Response.BinaryWrite(ms.ToArray());
HttpContext.Current.Response.End();

不过上述方法在firefox上还是乱码

终极解决办法:

代码语言:javascript
复制
                Encoding encoding;
                string outputFileName = null;
                string browser = HttpContext.Current.Request.UserAgent.ToUpper();
                if (browser.Contains("MS") == true && browser.Contains("IE") == true)
                {
                    outputFileName = HttpUtility.UrlEncode(fileName);
                    encoding = System.Text.Encoding.Default;
                }
                else if (browser.Contains("FIREFOX") == true)
                {
                    outputFileName = fileName;
                    encoding = System.Text.Encoding.GetEncoding("GB2312");
                }
                else
                {
                    outputFileName = HttpUtility.UrlEncode(fileName);
                    encoding = System.Text.Encoding.Default;
                }
                HttpContext.Current.Response.Clear();
                HttpContext.Current.Response.Buffer = true;
                HttpContext.Current.Response.ContentEncoding = encoding;
                HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xls", string.IsNullOrEmpty(outputFileName) ? DateTime.Now.ToString("yyyyMMddHHmmssfff") : outputFileName));
                HttpContext.Current.Response.BinaryWrite(ms.ToArray());
                HttpContext.Current.Response.End();
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2014-07-28 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档