为什么从 ASP.NET 页面下载 .docx 文件时会损坏?

2024-02-24

我有以下代码用于将页面附件带给用户:

private void GetFile(string package, string filename)
{
    var stream = new MemoryStream();

    try
    {
        using (ZipFile zip = ZipFile.Read(package))
        {
            zip[filename].Extract(stream);
        }
    }
    catch (System.Exception ex)
    {
        throw new Exception("Resources_FileNotFound", ex);
    }

    Response.ClearContent();
    Response.ClearHeaders();
    Response.ContentType = "application/unknown";

    if (filename.EndsWith(".docx"))
    {
        Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
    }

    Response.AddHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
    Response.BinaryWrite(stream.GetBuffer());
    stream.Dispose();
    Response.Flush();
    HttpContext.Current.ApplicationInstance.CompleteRequest();
}

问题是所有受支持的文件都可以正常工作(jpg、gif、png、pdf、doc 等),但 .docx 文件在下载时已损坏,需要由 Office 修复才能打开。

起初我不知道问题是否出在解压缩包含 .docx 的 zip 文件时,因此我没有将输出文件仅放在响应中,而是先保存了它,并且文件成功打开,所以我知道问题所在应该在写回复时。

你知道会发生什么吗?


我也遇到了这个问题,实际上找到了答案here http://www.aspmessageboard.com/showthread.php?t=230778:

原来docx格式需要有Response.End()就在之后Response.BinaryWrite.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么从 ASP.NET 页面下载 .docx 文件时会损坏? 的相关文章

随机推荐