How to force browser to download, not view, PDF documents in ASP.NET Webforms

14,146

Solution 1

Use a linkbutton so you can run serverside code on click:

<asp:LinkButton ID="hl_download" runat="server" OnClick="hl_download_Click">Download</asp:LinkButton>

Then, in the codebehind:

public void hl_download_Click(Object sender, EventArgs e)
{
    Response.AddHeader("Content-Type", "application/octet-stream");
    Response.AddHeader("Content-Transfer-Encoding","Binary");
    Response.AddHeader("Content-disposition", "attachment; filename=\"IdeaPark_ER_diagram.pdf\"");
    Response.WriteFile(HttpRuntime.AppDomainAppPath + @"ideaPark\DesktopModules\ResourceModule\pdf_resources\IdeaPark_ER_diagram.pdf");
    Response.End();
}

This assumes that the web path maps cleanly to the filesystem path of the file. Otherwise modify Response.WriteFile() so that it points to the location of the pdf file on the filesystem.

Solution 2

I had this same problem a few days ago and found a great solution posted by another here on StackOverflow. It's not 100% the same scenario as it uses HttpRequests to get files on another server, but sending the file to the browser in an octet-stream will guarantee a download window to pop.

Download/Stream file from URL - asp.net

Share:
14,146
Admin
Author by

Admin

Updated on June 15, 2022

Comments

  • Admin
    Admin almost 2 years

    just want to ask how can I prevent the web Browser from View on Browser because every time user click the link to download it View in Browser

    asp.net controller 
    <li><asp:HyperLink ID="hl_download" runat="server" >Download</asp:HyperLink></li>
    html
    <a id="dnn_ctr932_View_hl_download" href="/ideaPark/DesktopModules/ResourceModule/pdf_resources/IdeaPark_ER_diagram.pdf">Download</a>