在CHROME中不完整地打开PDF

本文关键字:PDF CHROME | 更新日期: 2024-09-27 03:49:57

我试图在chrome中打开一个pdf文件,但在显示过程中,它似乎被卡在了中间的某个地方。该代码似乎可以工作,因为它可以在IE中打开PDF,不确定为什么它会卡在chrome中。屏幕将变灰,显示"正在加载"标志,并在7/8停止。该文件大约为6MB或更大。

    public static void ReturnPDF(byte[] contents)
    {
        var response = HttpContext.Current.Response;
        response.Clear();
        response.AppendHeader("Content-Disposition", "inline;filename=" + "abc.pdf");
        response.BufferOutput = true;
        response.ContentType = System.Net.Mime.MediaTypeNames.Application.Pdf;
        response.BinaryWrite(contents);
        response.Flush();
        response.Close();
        response.End();
    }

有什么想法吗?感谢

[更新]

我尝试了版本30.0的firefox,它很有效。我的IE是8.0.7601.17514,也可以打开pdf。我的Chrome是39.0.2171.95。不确定浏览器的版本是否重要,这里只有chrome无法打开内联PDF。。。

〔已解决〕

添加内容长度后,chrome可以打开内联PDF。

   public static void ReturnPDF(byte[] contents)
    {
        var response = HttpContext.Current.Response;
        response.Clear();
        response.AppendHeader("Content-Disposition", "inline;filename=" + "abc.pdf");
        //After adding Content-Length, chrome is able to open PDF inline
        response.AppendHeader("Content-Length", contents.Length.ToString());
        response.BufferOutput = true;
        response.ContentType = System.Net.Mime.MediaTypeNames.Application.Pdf;
        response.BinaryWrite(contents);
        response.Flush();
        response.Close();
        response.End();
    }

在CHROME中不完整地打开PDF

OP的原始代码创建了如下响应:

response.Clear();
response.AppendHeader("Content-Disposition", "inline;filename=" + "abc.pdf");
response.BufferOutput = true;
response.ContentType = System.Net.Mime.MediaTypeNames.Application.Pdf;
response.BinaryWrite(contents);
response.End();

此代码尤其不会设置内容长度标头。一些没有该标题的网络浏览器版本(不仅是Chrome,还有其他浏览器的某些版本)往往会过早地认为下载已经完成。

如果既没有提供非标识传输编码也没有提供内容长度,则在最初创建为持久的连接上检测下载何时完成可能并非易事。

因此,这里的解决方案是添加

response.AppendHeader("Content-Length", contents.Length.ToString());

在写入CCD_ 1之前。

尝试使用"内容处置:附件"标头。

感谢mkl的建议。

我在标题中添加了内容长度,pdf可以在Chrome中成功打开!