下载文件乱码问题,并提供转码方法
不知大家遇没遇到过这种情况,大多数浏览器下载文件时,弹出的下载框上的文件名都是正常,唯独火狐或IE文件名显示乱码,这种情况一般不用解决,直接下载下来就行了,因为内容不是乱码,可以正常阅读取用,不过如果遇到特别较真的,特别爱钻牛角尖的朋友呢?不解决睡不着觉呀,为了挽救这些爱钻牛角尖的朋友,列出如下代码:
直接调用ToHexString(string s)方法即可:
protected void Page_Load(object sender, EventArgs e) { DocControl dc = new DocControl(); File file = dc.GetFile(FileID); if (file == null) return; if (!System.IO.File.Exists(System.IO.Path.Combine(HttpPath, file.FilePath))) { Response.Write("文件不存在"); Response.End(); } byte[] filesoure = System.IO.File.ReadAllBytes(System.IO.Path.Combine(HttpPath, file.FilePath)); if (filesoure != null) { string _fileExtension = file.FileExtension.Substring(1); Response.ContentType = _fileExtension; string _fileName = file.FleName; if (Request.UserAgent.Contains("MSIE 7.0") || Request.UserAgent.Contains("msie 7.0")) { if (_fileName.Length > 16) _fileName = _fileName.Substring(0, 12) + "." + _fileExtension; } _fileName = ToHexString(_fileName); Response.AddHeader("content-disposition", "inline;filename=" + _fileName); Response.AppendHeader("Content-Type", _fileExtension); Response.AddHeader("Content-Length", "" + filesoure.Length); Response.BinaryWrite(filesoure); Response.Flush(); Response.End(); } } /// <summary> /// 为字符串中的非英文字符编码 /// </summary> /// <param name="s"></param> /// <returns></returns> public string ToHexString(string s) { char[] chars = s.ToCharArray(); StringBuilder builder = new StringBuilder(); for (int index = 0; index < chars.Length; index++) { bool needToEncode = NeedToEncode(chars[index]); if (needToEncode) { string encodedString = ToHexString(chars[index]); builder.Append(encodedString); } else { builder.Append(chars[index]); } } return builder.ToString(); } /// <summary> ///指定 一个字符是否应该被编码 /// </summary> /// <param name="chr"></param> /// <returns></returns> private bool NeedToEncode(char chr) { string reservedChars = "$-_.+!*'(),@=&"; if (chr > 127) return true; if (char.IsLetterOrDigit(chr) || reservedChars.IndexOf(chr) >= 0) return false; return true; } /// <summary> /// 为非英文字符串编码 /// </summary> /// <param name="chr"></param> /// <returns></returns> private string ToHexString(char chr) { UTF8Encoding utf8 = new UTF8Encoding(); byte[] encodedBytes = utf8.GetBytes(chr.ToString()); StringBuilder builder = new StringBuilder(); for (int index = 0; index < encodedBytes.Length; index++) { builder.AppendFormat("%{0}", Convert.ToString(encodedBytes[index], 16)); } return builder.ToString(); } private string NewString(string str) { string filename = System.IO.Path.GetFileNameWithoutExtension(str); return ToHexString(filename); }