#问题:客户端为ie或Firefox,服务端为asp.net时,下载文件名中包含中文汉字时,下载下来的文件的文件名是乱码;
#解决方案:
示例代码:下载名称中带汉字的文件;
1 public void ProcessRequest(HttpContext context) 2 { 3 string action = context.Request["action"].ToString(); 4 if (action == "download") 5 { 6 string fileName = "资源统计详细信息.txt";//客户端保存的文件名 7 string filePath = context.Server.MapPath("资源统计详细信息.txt");//服务端文件路径 8 9 //以字符流的形式下载文件 10 FileStream fs = new FileStream(filePath, FileMode.Open); 11 byte[] bytes = new byte[(int)fs.Length]; 12 fs.Read(bytes, 0, bytes.Length); 13 fs.Close(); 14 15 #region 处理中文文件名乱码问题(ie及firefox下) 16 Encoding encoding; 17 string outputFileName = null; 18 string browser = HttpContext.Current.Request.UserAgent.ToUpper(); 19 if (browser.Contains("MS") == true && browser.Contains("IE") == true) 20 { 21 outputFileName = HttpUtility.UrlEncode(fileName); 22 encoding = System.Text.Encoding.Default; 23 } 24 else if (browser.Contains("FIREFOX") == true) 25 { 26 outputFileName = fileName; 27 encoding = System.Text.Encoding.GetEncoding("GB2312"); 28 } 29 else 30 { 31 outputFileName = HttpUtility.UrlEncode(fileName); 32 encoding = System.Text.Encoding.Default; 33 } 34 #endregion 35 36 HttpContext.Current.Response.Clear(); 37 HttpContext.Current.Response.Buffer = true; 38 HttpContext.Current.Response.ContentEncoding = encoding; 39 HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.txt", string.IsNullOrEmpty(outputFileName) ? DateTime.Now.ToString("yyyyMMddHHmmssfff") : outputFileName)); 40 HttpContext.Current.Response.BinaryWrite(bytes); 41 HttpContext.Current.Response.End(); 42 43 } 44 }
------------------------------