簡體   English   中英

PDF 文件未在 .aspx 頁面上下載為 pdf

[英]PDF file not downloading as pdf on .aspx page

所以我有一個代碼可以使用以下代碼預覽 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 上查看: 看圖

它將文件下載為 .aspx 而不是 .pdf。 這僅發生在 chrome 中,而不發生在 IE 或 Edge 中。

我試過Response.AddHeader("content-disposition", "attachment; filename=myPDFfile.pdf"); 並且此自動下載文件不會允許它在下載前查看。 任何幫助表示贊賞謝謝!

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(); 
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM