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

时间:2023-03-09 21:38:41
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) != -)
{
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();
}
}