Asp.net 来自asp应用程序的流式mime类型“application/pdf”在Google Chrome中失败

Asp.net 来自asp应用程序的流式mime类型“application/pdf”在Google Chrome中失败,asp.net,google-chrome,mime-types,Asp.net,Google Chrome,Mime Types,我有一个web应用程序,可以在点击事件中传输PDF文件,它在IE、Firefox和Safari中运行良好,但在Chrome中它从不下载。下载被中断了。Chrome处理流媒体的方式不同吗?我的代码如下所示: this.Page.Response.Buffer = true; this.Page.Response.ClearHeaders(); this.Page.Response.ClearContent(); this.Page.R

我有一个web应用程序,可以在点击事件中传输PDF文件,它在IE、Firefox和Safari中运行良好,但在Chrome中它从不下载。下载被中断了。Chrome处理流媒体的方式不同吗?我的代码如下所示:

        this.Page.Response.Buffer = true;
        this.Page.Response.ClearHeaders();
        this.Page.Response.ClearContent();
        this.Page.Response.ContentType = "application/pdf";
        this.Page.Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName);
        Stream input = reportStream;
        Stream output = this.Page.Response.OutputStream;
        const int Size = 4096;
        byte[] bytes = new byte[4096];
        int numBytes = input.Read(bytes, 0, Size);
        while (numBytes > 0)
        {
            output.Write(bytes, 0, numBytes);
            numBytes = input.Read(bytes, 0, Size);
        }

        reportStream.Close();
        reportStream.Dispose();
        this.Page.Response.Flush();
        this.Page.Response.Close();

有没有关于我可能遗漏什么的建议?

这只是一个猜测。在chrome中,当您在HTTP头中的Accept或Content Type中指定了多种格式时,它会使用逗号(而不是分号)来分隔这些格式。分号是标准格式。当使用逗号表示时,一些框架实际上几乎每个框架都无法解析并抛出堆栈跟踪。您可以通过在chrome中使用firebug来验证这一点。

最近发布的Google chrome v12版本触发了您描述的问题

您可以通过发送Content-Length标头来修复它,如下代码的修改版本所示:

this.Page.Response.Buffer = true;
this.Page.Response.ClearHeaders();
this.Page.Response.ClearContent();
this.Page.Response.ContentType = "application/pdf";
this.Page.Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName);
Stream input = reportStream;
Stream output = this.Page.Response.OutputStream;
const int Size = 4096;
byte[] bytes = new byte[4096];
int totalBytes = 0;
int numBytes = input.Read(bytes, 0, Size);
totalBytes += numBytes;
while (numBytes > 0)
{
    output.Write(bytes, 0, numBytes);
    numBytes = input.Read(bytes, 0, Size);
    totalBytes += numBytes;
}

// You can set this header here thanks to the Response.Buffer = true above
// This header fixes the Google Chrome bug
this.Page.Response.AddHeader("Content-Length", totalBytes.ToString());

reportStream.Close();
reportStream.Dispose();
this.Page.Response.Flush();
this.Page.Response.Close();

Chrome似乎倾向于将请求拆分,并将文件分块请求。这可能是您的问题的症结所在,这与我有关。

适用于Android和Chrome:Android和HTTP下载文件头