现在的位置: 首页 > 综合 > 正文

下载文件,中文名称显示为乱码,解决方案记录

2013年09月09日 ⁄ 综合 ⁄ 共 3318字 ⁄ 字号 评论关闭
  public Stream Download(string fileserviceid, string path, string fileName, string originalFileName, string preview)
        {
            if (string.IsNullOrEmpty(path) || string.IsNullOrEmpty(fileName))
                return default(Stream);

            string tempFilePath = Path.Combine(ConfigurationManager.AppSettings["FileServiceRoot" + fileserviceid], path, "files", string.Format("{0}{1}", fileName, Path.GetExtension(originalFileName)));

            if (File.Exists(tempFilePath))
            {
                var outgoingResponse = System.Web.HttpContext.Current.Response;

                outgoingResponse.ContentType = MapContentType(Path.GetExtension(originalFileName));

                Encoding code = Encoding.GetEncoding("gb2312");
                outgoingResponse.ContentEncoding = code;
                outgoingResponse.HeaderEncoding = code;//这句很重

                outgoingResponse.AddHeader("Content-Disposition", "attachment;filename=" + originalFileName);

                //记录log
                Stream result = new FileStream(tempFilePath, FileMode.Open, FileAccess.Read, FileShare.Read);
                return result;
            }
            else
            {
                return default(Stream);
            }
        }

转载一篇,备用:

最近在Asp.net项目中遇到一个问题,实现文件下载时,英文文件名的文件下载时,文件名显示正常,但是如果文件名为中文则显示乱码。

 

在网上google了一下,找到这编文章:解决用ASP.NET下载文件时,文件名为乱码的问题

string encodefileName= System.Web.HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8); //通过使用HttpUtility.UrlEncode()来对原始文件名进行编码,以解决文件名乱码
Response.AppendHeader("content-disposition", "attachment;filename=" + encodefileName);//附件下载

但是以上这个方案,存在一个问题:就是如果文件名中有空格则空格变成了“+” 号,其他特殊字符尚未测试,有可能还存在其他问题。

 

再次使用google,终于找到老外的一编文章:Display a non-US-ASCII filename in File Download dialog box

他使用如下code解决问题:

string encodefileName=ToHexString(fileName);       //使用自定义的ToHexString()方法,编码原始文件名

Response.AppendHeader("content-disposition", "attachment;filename=" + encodefileName);

        /// <summary>
        /// Encodes non-US-ASCII characters in a string.
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static 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>
        /// Determines if the character needs to be encoded.
        /// </summary>
        /// <param name="chr"></param>
        /// <returns></returns>
        private static bool NeedToEncode(char chr)
        {
            string reservedChars = "$-_.+!*'(),@=&";

            if (chr > 127)
                return true;
            if (char.IsLetterOrDigit(chr) || reservedChars.IndexOf(chr) >= 0)
                return false;

            return true;
        }

        /// <summary>
        /// Encodes a non-US-ASCII character.
        /// </summary>
        /// <param name="chr"></param>
        /// <returns></returns>
        private static 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();
        }

抱歉!评论已关闭.