服务器启用了gizp,下载的excel模版会出现问题,怎么解决?

事理 2013-09-09 04:39:32
服务器相关参数:
IIS6.0
.net frmework3.5
启用IIS gzip压缩网站,压缩的参数里面没有包含xls后缀名

没有启用gizp时下载是正常了,启用了gizp就出现表头不见了,网上查找了下http://www.cnblogs.com/ppchen/archive/2009/02/19/1382530.html 里面是使用HttpModule
只有使用HttpModule这种方法吗?


下载文件代码

/// <summary>
/// 下载指定路径文件
/// </summary>
/// <param name="path">文件绝对路径</param>
public static void DownLoadFile(string path, string oldFileName)
{
System.IO.FileInfo fi = new System.IO.FileInfo(path);
if (fi.Exists)
{
//判断文件是否正在使用
try
{
using (System.IO.FileStream fs = System.IO.File.Open(path, System.IO.FileMode.Append, System.IO.FileAccess.Write, System.IO.FileShare.None))
{
}
}
catch (Exception)
{
throw;
}

if (string.IsNullOrEmpty(oldFileName))
oldFileName = path.Substring(path.LastIndexOf("\\") + 1);

string browser = System.Web.HttpContext.Current.Request.UserAgent.ToUpper();
if (browser.Contains("FIREFOX") == true)
oldFileName = "\"" + oldFileName + "\"";
else if (browser.Contains("MSIE"))
oldFileName = ToHexString(oldFileName);
else
oldFileName = HttpUtility.UrlEncode(oldFileName);

System.Web.HttpContext.Current.Response.Clear();
System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + oldFileName);
System.Web.HttpContext.Current.Response.AddHeader("Content-Length", fi.Length.ToString());
System.Web.HttpContext.Current.Response.ContentType = "application/octet-stream;charset=gb2321";
System.Web.HttpContext.Current.Response.WriteFile(fi.FullName);
System.Web.HttpContext.Current.Response.Flush();
System.Web.HttpContext.Current.Response.Close();
}
else
{
throw new Exception("文件在服务器上不存在!");
}
}

...全文
286 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
事理 2013-10-08
  • 打赏
  • 举报
回复
最终解决方法

#region 下载指定路径文件

    /// <summary>
    /// 下载指定路径文件
    /// </summary>
    /// <param name="path">文件绝对路径</param>
    public static void DownLoadFile(string path, string oldFileName)
    {
        System.IO.FileInfo fi = new System.IO.FileInfo(path);
        if (fi.Exists)
        {
            //判断文件是否正在使用
            try
            {
                using (System.IO.FileStream fs = System.IO.File.Open(path, System.IO.FileMode.Append, System.IO.FileAccess.Write, System.IO.FileShare.None))
                {
                }
            }
            catch (Exception)
            {
                throw;
            }

            if (string.IsNullOrEmpty(oldFileName))
                oldFileName = path.Substring(path.LastIndexOf("\\") + 1);

            string browser = System.Web.HttpContext.Current.Request.UserAgent.ToUpper();
            if (browser.Contains("FIREFOX") == true)
                oldFileName = "\"" + oldFileName + "\"";
            else if (browser.Contains("MSIE"))
                oldFileName = ToHexString(oldFileName);
            else
                oldFileName = HttpUtility.UrlEncode(oldFileName, System.Text.Encoding.UTF8);

            System.Web.HttpContext.Current.Response.Clear();
            System.Web.HttpContext.Current.Response.AppendHeader("Content-Encoding", "no");//解决服务器启用gizp后文件下载出错问题
            System.Web.HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=" + oldFileName);
            System.Web.HttpContext.Current.Response.AddHeader("Content-Length", fi.Length.ToString());
            System.Web.HttpContext.Current.Response.TransmitFile(fi.FullName);
            System.Web.HttpContext.Current.Response.Flush();
            System.Web.HttpContext.Current.Response.Close();
        }
        else
        {
            throw new Exception("文件在服务器上不存在!");
        }
    }

    /// <summary>
    /// 为字符串中的非英文字符编码
    /// </summary>
    /// <param name="s"></param>
    /// <returns></returns>
    public static string ToHexString(string s)
    {
        char[] chars = s.ToCharArray();
        System.Text.StringBuilder builder = new System.Text.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)
    {
        System.Text.UTF8Encoding utf8 = new System.Text.UTF8Encoding();
        byte[] encodedBytes = utf8.GetBytes(chr.ToString());
        System.Text.StringBuilder builder = new System.Text.StringBuilder();
        for (int index = 0; index < encodedBytes.Length; index++)
        {
            builder.AppendFormat("%{0}", Convert.ToString(encodedBytes[index], 16));
        }
        return builder.ToString();
    }
   
    #endregion
事理 2013-09-09
  • 打赏
  • 举报
回复
引用 7 楼 sp1234 的回复:
晕! 那你写成 System.Web.HttpContext.Current.Response.ContentType = "application/octet-stream;charset=gb2321" 这个头是要干什么啊?
是防止下载文件的时候文件名变为乱码
事理 2013-09-09
  • 打赏
  • 举报
回复
谢谢楼上两位的回复,并不是下载文件方法法的问题,顺便共享一下下载文件的全部代码,支持火狐、ie等,中文名称不乱码,

    /// <summary>
    /// 为字符串中的非英文字符编码
    /// </summary>
    /// <param name="s"></param>
    /// <returns></returns>
    public static string ToHexString(string s)
    {
        char[] chars = s.ToCharArray();
        System.Text.StringBuilder builder = new System.Text.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)
    {
        System.Text.UTF8Encoding utf8 = new System.Text.UTF8Encoding();
        byte[] encodedBytes = utf8.GetBytes(chr.ToString());
        System.Text.StringBuilder builder = new System.Text.StringBuilder();
        for (int index = 0; index < encodedBytes.Length; index++)
        {
            builder.AppendFormat("%{0}", Convert.ToString(encodedBytes[index], 16));
        }
        return builder.ToString();
    }

  • 打赏
  • 举报
回复
晕! 那你写成 System.Web.HttpContext.Current.Response.ContentType = "application/octet-stream;charset=gb2321" 这个头是要干什么啊?
事理 2013-09-09
  • 打赏
  • 举报
回复
解决了,在IIS中的http头——MIME映射中的文件类型——添加新类型.xls,application/vnd.ms-excel即可
事理 2013-09-09
  • 打赏
  • 举报
回复
感觉和下载的代码没什么关系,在没有启用gizp的时候下载都是正常的,明天试下
H_Gragon 2013-09-09
  • 打赏
  • 举报
回复
同意楼上!
Andy__Huang 2013-09-09
  • 打赏
  • 举报
回复
public static void ResponseApplicationFile(this HttpContext context, string filePath, string saveAsName, bool isDirectOpen = false)
{
    HttpResponse Response = context.Response;
    Response.Clear();
    Response.Buffer = true;
    Response.ContentType = MIMEUtility.GetMIMEType(filePath);
    string downloadFileSaveAsName = string.Empty;
    if (string.IsNullOrWhiteSpace(System.IO.Path.GetFileNameWithoutExtension(saveAsName)) || string.IsNullOrWhiteSpace(saveAsName))
    {
        downloadFileSaveAsName = System.IO.Path.GetFileName(filePath);
    }
    else if (System.IO.Path.GetExtension(filePath).ToUpper() == System.IO.Path.GetExtension(saveAsName))
    {
        downloadFileSaveAsName = saveAsName;
    }
    else
    {
        downloadFileSaveAsName = saveAsName + System.IO.Path.GetExtension(filePath);
    }
    Response.HeaderEncoding = Encoding.UTF8;
    if (System.IO.File.Exists(filePath))
    {
        Response.AddHeader("content-disposition", (isDirectOpen ? "" : "attachment;") + " filename=" + HttpUtility.UrlEncode(downloadFileSaveAsName, Encoding.UTF8) + ";size=" + (new FileInfo(filePath)).Length.ToString());
        byte[] contents = System.IO.File.ReadAllBytes(filePath);
        Response.BinaryWrite(contents);
    }
    else
    {
        Response.AddHeader("content-disposition", (isDirectOpen ? "" : "attachment;") + "filename=" + HttpUtility.UrlEncode(downloadFileSaveAsName, Encoding.UTF8) + ";size=0");
    }
    Response.Flush();
    Response.End();
}
然后这样调用:

protected void Page_Load(object sender, EventArgs e)
{
    this.Button_DownloadTemplateFile.Click += new EventHandler(Button_DownloadTemplateFile_Click);
}

void Button_DownloadTemplateFile_Click(object sender, EventArgs e)
{
    string filename = "xxxxxx.xls";
    string DownloadFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory+EnvironmentSetting.ThankyouLetterPath, filename);
    if (!System.IO.File.Exists(DownloadFilePath))
    {
        this.MessageBoxLayer.Show("找不到相關檔案");
        return;
    }
    byte[] contents = System.IO.File.ReadAllBytes(DownloadFilePath);
    FileInfo info = new FileInfo(DownloadFilePath);
    long fileSize = info.Length;
    this.Context.ResponseApplicationFile(DownloadFilePath, filename);
}
Andy__Huang 2013-09-09
  • 打赏
  • 举报
回复
我觉得你方法有问题,你还去判断文件是否有人使用。你应该先把模板文件copy到一个临时目录下,然后再对这个文件进行写数据,这样才能保证没有问题
事理 2013-09-09
  • 打赏
  • 举报
回复
有没有人知道

62,046

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术交流专区
javascript云原生 企业社区
社区管理员
  • ASP.NET
  • .Net开发者社区
  • R小R
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

.NET 社区是一个围绕开源 .NET 的开放、热情、创新、包容的技术社区。社区致力于为广大 .NET 爱好者提供一个良好的知识共享、协同互助的 .NET 技术交流环境。我们尊重不同意见,支持健康理性的辩论和互动,反对歧视和攻击。

希望和大家一起共同营造一个活跃、友好的社区氛围。

试试用AI创作助手写篇文章吧