编码--IE7下无法下载附件

执行下面的代码:

string _fileName="热烈庆祝中国共产党成立90周年.doc";

Response.AddHeader("content-disposition", "attachment;filename=" + _fileName);
Response.AppendHeader("Content-Type", _fileExtension);
Response.AddHeader("Content-Length", "" + filesoure.Length);
Response.BinaryWrite(filesoure);
Response.Flush();
Response.End();

报错提示如下:

Internet Explorer 无法下载 Download.aspx。来自***.***.***.***
Internet Explorer 无法打开该 Internet 站点。请求的站点不可用,或找不到。请以后再试。

原因分析:

_fileName未做编码处理。

解决方法:

给_fileName做编码处理。即_fileName = ToHexString(_fileName);


编码方法处理过程如下:

        /// <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);

        }

你可能感兴趣的:(编码,职场,ie7,休闲)