8

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>
AlliterativeAlice
  • 11,841
  • 9
  • 52
  • 69
  • this is a user setting. don't mess with the user. If I used your site and I didn't get the expected behaviour I would be annoyed. – skyfoot Aug 20 '13 at 15:38
  • I know that but our client request that –  Aug 20 '13 at 15:56
  • you fake the pdf download as a download instead of a pdf document by sending a header `Content-Type: application/octet-stream`, here's how you do it in php http://stackoverflow.com/questions/7263923/how-to-force-file-download-with-php – SSpoke Aug 20 '13 at 15:59
  • that's PHP my problem is in .net –  Aug 20 '13 at 16:05
  • 1
    possible duplicate of [How to force a pdf download automatically?](http://stackoverflow.com/questions/2598658/how-to-force-a-pdf-download-automatically) – Quentin Aug 20 '13 at 16:33
  • A good example: http://www.c-sharpcorner.com/uploadfile/afenster/how-to-download-a-file-in-asp-net/ – Eduardo Cuomo Sep 25 '14 at 17:42

2 Answers2

18

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.

Mark Cooper
  • 6,738
  • 5
  • 54
  • 92
AlliterativeAlice
  • 11,841
  • 9
  • 52
  • 69
1

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

Community
  • 1
  • 1
Lucky Pierre
  • 570
  • 4
  • 18