C# 字符流返回文件下载时 文件中文名乱码处理

来源:互联网 发布:淘宝天下网商店小二 编辑:程序博客网 时间:2024/06/04 20:50

如下在后台代码HttpContext.Current.Response返回文件流前做如下处理即可:

           var fileName = "中文文件名.doc";

            string modPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileName);
            if (!System.IO.File.Exists(modPath))
                return;
            try
            {
                FileInfo fileinfo = new FileInfo(modPath);
                HttpContext.Current.Response.Clear(); //清除缓冲区流中的所有内容输出
                HttpContext.Current.Response.ClearContent(); //清除缓冲区流中的所有内容输出
                HttpContext.Current.Response.ClearHeaders(); //清除缓冲区流中的所有头

                HttpContext.Current.Response.Buffer = true; //该值指示是否缓冲输出,并在完成处理整个响应之后将其发送

               //在如下对中文转码

                HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpContext.Current.Server.UrlEncode(fileName));
                HttpContext.Current.Response.AddHeader("Content-Length", fileinfo.Length.ToString());
                HttpContext.Current.Response.AddHeader("Content-Transfer-Encoding", "binary");

                HttpContext.Current.Response.ContentType = "application/unknow"; 

                //获取或设置输出流的 HTTP MIME 类型

                HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Default;
                HttpContext.Current.Response.Buffer = true;
                HttpContext.Current.Response.ContentType = "application/x-zip-compressed";
                HttpContext.Current.Response.AddHeader("Accept-Language", "zh-cn");
               //获取或设置输出流的 HTTP 字符集
                HttpContext.Current.Response.TransmitFile(modPath);
                HttpContext.Current.Response.End();
            }
            catch (Exception ex)

            {

               //

            }
原创粉丝点击