简体   繁体   中英

PDF file not downloading as pdf on .aspx page

so I have a code that previews a PDF file using this code:

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

It views PDF file fine in chrome, IE, and Edge but on chrome when I do a download using these options: 看图

It downloads the file as .aspx not .pdf. This is only happening in chrome not in IE or Edge.

I have tried Response.AddHeader("content-disposition", "attachment; filename=myPDFfile.pdf"); and this auto downloads the file wont allow it to be able to view before download. Any help is appreciated thank!

Chrome's built in PDF viewer download button points to the PDF's origin URL, so in your case the aspx page. A potential solution to this issue would to create an new aspx page that loads the PDF on page_load, and then target the new page.

Not sure how your original code block is being called, but you should be able to either insert the target page with an <a> anchor tag or use Response.Redirect() .

Example target page load:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM