在ASP.Net网站中,Android手机在回发后无法打开流式传输的PDF文件。

4

我有一个ASP.NET网站,它在初次请求页面后返回一个PDF文档。在IE、Chrome、Firefox以及iPhone和iPad上,一切正常,PDF被发送到浏览器。但是在安卓手机上,会出现“PDF无效”的错误。下面的代码简化了我正在尝试的操作,但它可以复现这个错误。我基本上有一个按钮放在一个网页上,设置为在服务器上运行。在第一次请求页面时显示HTML,在按钮单击后,应该呈现PDF:

protected void Page_Load(object sender, EventArgs e)
{

    Response.ClearHeaders();
    Response.AppendHeader("Cache-Control", "no-cache"); //HTTP 1.1
    Response.AppendHeader("Cache-Control", "private"); // HTTP 1.1
    Response.AppendHeader("Cache-Control", "no-store"); // HTTP 1.1
    Response.AppendHeader("Cache-Control", "must-revalidate"); // HTTP 1.1
    Response.AppendHeader("Cache-Control", "max-stale=0"); // HTTP 1.1 
    Response.AppendHeader("Cache-Control", "post-check=0"); // HTTP 1.1 
    Response.AppendHeader("Cache-Control", "pre-check=0"); // HTTP 1.1 
    Response.AppendHeader("Pragma", "no-cache"); // HTTP 1.1 
    Response.AppendHeader("Keep-Alive", "timeout=3, max=993"); // HTTP 1.1 
    Response.AppendHeader("Expires", "0"); // HTTP 1.1 

    if (IsPostBack)
    {
        Response.ClearContent();
        Response.ClearHeaders();

        string fullPath = @"C:\Temp\outdoc.pdf";

        if (System.IO.File.Exists(fullPath))
        {

            //Set the appropriate ContentType.
            Response.ContentType = "application/pdf";
            //Response.ContentType = "application/octet-stream";
            Response.AddHeader("Content-Disposition", "attachment;filename=\"TestDoc.pdf\"");

            byte[] b = System.IO.File.ReadAllBytes(fullPath);
            this.Page.Response.AddHeader("Content-Length", b.Length.ToString());

            //Write the file directly to the HTTP content output stream.
            Response.BinaryWrite(b);
            Response.Flush();
            Response.End();
            Response.Close();

        }
    }


}

我已经尝试了不同的标头值和关闭、刷新响应流的不同方法,但都没有成功。有人遇到过这种情况吗?或者能否提供一些尝试的建议。

编辑:我发现只有在页面进行 postback 时才会出现此问题。如果我直接流式传输文档,则文档会正确地流式传输。这让我觉得这可能是 Android 浏览器缓存问题。

2个回答

1

尝试将当前请求转移到其他处理程序,您可以直接将PDF渲染到响应流中。

您的页面代码:

if (IsPostBack)
{
  Context.Server.Transfer("RenderPDF.ashx");
  Response.End();
}

在新的RenderPDF.ashx文件中,将负责渲染PDF文件的代码移动到这里。


谢谢。我会尝试一下并告诉你结果。 - John Koerner

0

从我所了解的情况来看,Android似乎不太喜欢Content-Disposition。我建议将PDF写入文件并发出重定向到指向该文件的URL。


这对我来说不是一个好的解决方案,因为在我的真正解决方案中,我正在从数据库流式传输数据以创建PDF,并且我不希望在服务器上留下临时副本。然后,我会遇到很多清理文件和确保名称唯一性的问题。此外,如果我不进行回发,这似乎不是一个问题,我已经发现并将其添加到原始帖子中。 - John Koerner
@John Koerner:“我不想让一个临时副本停留在服务器上”--将其放入特定目录,并使用cron作业每晚清理旧的PDF文件。“并确保名称的唯一性”--使用GUID。 - CommonsWare
问题在于,我正在根据用户的输入解密一些数据,但我不能让解密后的数据在服务器文件系统上存留任何时间。 - John Koerner

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接