asp.net 文件下载 解决文件名乱码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;


using ElementLibrary.BLL;
using ElementLibrary.MODEL;
using System.Text;
/*
 * LiuH
 * Descr:下载处理DownLoadFile.ashx
 * Addtime:2014/8/26
 * LastModifyTime:2014/8/27
 */
namespace ElementLibrary.Web.Action
{
    /// <summary>
    ///DownLoadFile 的摘要描述
    /// </summary>
    public class DownLoadFile : IHttpHandler
    {
        ElementDetailBLL elementDetailBLL = new ElementDetailBLL();
        public void ProcessRequest(HttpContext context)
        {
            string strFunId = context.Request.QueryString["id"].ToString();//获取方法id(元件ID)
            MODEL.ElementDetailInfo elementDetailInfo = elementDetailBLL.GetAllContent(strFunId);//客户端保存的文件名
            string fileName = elementDetailInfo.FileName;
            string strFilePath = elementDetailInfo.FilePath;
            string filePath = context.Server.MapPath(strFilePath);//路径
            FileInfo fileInfo = new FileInfo(filePath);
            context.Response.Clear();
            context.Response.ClearContent();
            context.Response.ClearHeaders();
           //解决文件名乱码(LiuH AddTime:2014/8/28)
            if (context.Request.UserAgent.Contains("MSIE") || context.Request.UserAgent.Contains("msie"))
            {
                // 如果客户端使用 Microsoft Internet Explorer,则需要编码
                 fileName = ToHexString(fileName); 
            }
            context.Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
            context.Response.AddHeader("Content-Length", fileInfo.Length.ToString());
            context.Response.AddHeader("Content-Transfer-Encoding", "binary");
            context.Response.ContentType = "application/octet-stream";
            context.Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
            context.Response.WriteFile(fileInfo.FullName);
            context.Response.Flush();
            //fileInfo.Delete();
            context.Response.End();
        }

        /// <summary>
        /// 为字符串中的非英文字符编码
        /// </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>
        ///指定 一个字符是否应该被编码
        /// </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>
        /// 为非英文字符串编码
        /// </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();
        }


        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

 

posted @ 2014-08-28 11:57  哼哼c#  阅读(602)  评论(0编辑  收藏  举报