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;
            }
        }
    }
}
时间: 2024-08-14 19:27:05

asp.net 文件下载 解决文件名乱码的相关文章

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  * LastModif

利用php CI force_download($filename, $data) 下载.csv 文件解决文件名乱码,文件内容乱码

利用php CI force_download($filename, $data) 下载.csv 文件解决文件名乱码,文件内容乱码.做了很久终于知道了很好的解决方案. 1.加载辅助函数 $this->load->helper('download'); //下载辅助函数 $this->load->helper('string'); //字符编码转换辅助翻书 2.force_download($filename, $data)通过它的代码可以知道$data 必须是字符串,如果不是字符串

java基础---&gt;文件---&gt;从标准输入读取字符串作为文件名----&gt;解决“文件名乱码”问题

概述:程序中有时会需要从标准输入读取字符串作为文件的名字,其具体实现方法有许多种.我第一次尝试编写这方面的程序时遇到了"乱码问题",后来使用了新的写法解决了乱码问题. /*原码,使用这种方法编写的代码会出现"乱码问题" 乱码原因分析:从标准输入读取的数据先被存放至byte[]中,之后又将byte数组转成String,这个过程中就会出现编码不一致的问题 如标准输入"file1",但是最终fileName=buffer.toString()的结果却是

java文件下载的文件名乱码

// //下载文件,并处理文件名乱码 public void downloadFile(HttpServletRequest request,HttpServletResponse response){    String path = request.getSession().getServletContext().getRealPath("/upload/文档1.doc");     // path是根据日志路径和文件名拼接出来的      File file = new File

文件下载中文文件名乱码

B/S应用中,下载一个附件保存时,中文文件名会乱码,在实际开发中经常遇到,现贴出C#和JAVA的解决方法: C#: Response.AppendHeader("Content-Disposition", "attachment;filename=" + Tools.toUtf8String(result)); 其中用到的转换方法: public static string ToUtf8String(String s) { StringBuilder sb = ne

文件下载之文件名乱码问题的工具类

package cn.itcast.down.utils; import java.io.IOException;import java.net.URLEncoder; import javax.servlet.http.HttpServletRequest; import sun.misc.BASE64Encoder;/* * 下载文件的工具类 */public class DownUtils { public static String filenameEncoding(String fil

文件下载文件名乱码解决

if(request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0){ response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode(product.getRealName1(), "UTF-8")); }else{ res

Struts2 .apk 文件下载及解决中文文件名乱码问题(转)

1.Tomcat服务器不能下载 .apk类型文件 Android的APK安装包不能下载或下载文件是以 .zip为后缀名而不是 .apk为文件后缀名时,需在 Tomcat 的 web.xml 配置文件中加入以下 MIME 类型: 1 <mime-mapping> 2 <extension>apk</extension> 3 <mime-type>application/vnd.android.package-archive</mime-type>

文件下载(解决下载文件文件名乱码)

不同浏览器下载文件时会出现文件名乱码问题,根据请求浏览器类型处理文件名.