PDF文件未在.aspx页上以pdf格式下载

时间:2019-02-04 17:51:50

标签: c# asp.net pdf download

所以我有一个使用此代码预览PDF文件的代码:

System.Net.WebClient client = new System.Net.WebClient();
        //text box holds the path to the original pdf file in a folder
        Byte[] Thisbuffer = client.DownloadData(TextBox.Text);

        if (Thisbuffer!= null)
        {
            Response.ContentType = "application/pdf";
            Response.AddHeader("content-length", Thisbuffer.Length.ToString());
            Response.BinaryWrite(Thisbuffer);
        }

当我使用以下选项进行下载时,它可以在chrome,IE和Edge上很好地查看PDF文件,但在chrome上可以查看: See image

它将文件下载为.aspx而不是.pdf。这仅在chrome中发生,而不在IE或Edge中发生。

我尝试过Response.AddHeader("content-disposition", "attachment; filename=myPDFfile.pdf");,并且此自动下载文件将使其无法在下载前查看。 任何帮助表示赞赏,谢谢!

1 个答案:

答案 0 :(得分:0)

Chrome 的内置 PDF 查看器下载按钮指向 PDF 的原始 URL,因此在您的情况下是 aspx 页面。此问题的一个潜在解决方案是创建一个新的 aspx 页面,在 page_load 上加载 PDF,然后定位到新页面。

不确定您的原始代码块是如何被调用的,但您应该能够使用 <a> 锚标记或使用 Response.Redirect() 插入目标页面。

示例目标页面加载:

protected void Page_Load(object sender, EventArgs e)
{
    if (Request.QueryString["RequestedPath"] != null)
    {
        System.Net.WebClient client = new System.Net.WebClient();
        //text box holds the path to the original pdf file in a folder
        Byte[] Thisbuffer = client.DownloadData(Request.QueryString["RequestedPath"]);

        if (Thisbuffer!= null)
        {
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.ClearHeaders();
            HttpContext.Current.Response.ClearContent();
            HttpContext.Current.Response.AddHeader("Content-Disposition", "filename=myPDFfile.pdf");
            HttpContext.Current.Response.AddHeader("content-length", Thisbuffer.Length.ToString());
            HttpContext.Current.Response.ContentType = "application/pdf";
            HttpContext.Current.Response.BinaryWrite(Thisbuffer);
            HttpContext.Current.Response.Flush();
            HttpContext.Current.Response.SuppressContent = true;
            HttpContext.Current.ApplicationInstance.CompleteRequest(); 
        }
    }
}
相关问题