Asp.net 解决下载乱码问题,支持火狐、IE、谷歌等主流浏览器

   public static void DownFileStream(MemoryStream ms, string fileName)
        {
            if (ms !=Stream.Null)
            {

                if (HttpContext.Current.Request.UserAgent != null && HttpContext.Current.Request.UserAgent.ToUpper().IndexOf("FIREFOX", StringComparison.Ordinal) != -1)
                {
                    fileName = "=?UTF-8?B?" + Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(fileName)) + "?=";
                }
                else
                {
                    fileName = System.Web.HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8);
                    if (fileName != null) fileName = fileName.Replace("+", "%20");
                }
                HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}.xls",fileName));
                HttpContext.Current.Response.AddHeader("Content-Length", ms.Length.ToString());
                HttpContext.Current.Response.AddHeader("Content-Transfer-Encoding", "binary");
                HttpContext.Current.Response.ContentType = "application/octet-stream;charset=utf-8";
                HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
                HttpContext.Current.Response.BinaryWrite(ms.ToArray());
                ms.Close();
                ms.Dispose();
            }
        }

 

posted @ 2016-08-15 16:17  潇潇与偕  阅读(697)  评论(1编辑  收藏  举报