Rishi Bharadwaj
Rishi Bharadwaj

Reputation: 2076

open dialog to download pdf

I have a gridview in which I have provided an option for the user to download the pdf files. When they click on the pdf icon sometimes it open the pdf file in a new tab and sometimes it starts downloading. How can i make it download always?

Upvotes: 0

Views: 1879

Answers (2)

Icarus
Icarus

Reputation: 63956

In order to always force a download you need to add the Content-Disposition header as AVD showed; however, I find this totally unnecessary; I think it would suffice to have the link to the PDF open in a new window. In other words, have target="_blank" defined. Example:

<a href="file.pdf" target="_blank">invoice</a>

Then, is up to the user whether he wants to save the file locally or just see it on the screen. I think the important thing is that this won't interfere with the current page the user is looking at.

Upvotes: 2

KV Prajapati
KV Prajapati

Reputation: 94625

You need to add a button (image button, linknbutton or button) and handle the RowCommand event of GridView. In RowCommand handler you may write code to download a file.

You may use Response object's method.

string filepath=MapPath("~/files/file.pdf");
byte []bytes=System.IO.File.ReadAllBytes(filepath);

Response.Clear();
Response.ClearHeaders();
Response.AddHeader("Content-Type", "application/octet-stream");
Response.AddHeader("Content-Length", bytes.Length.ToString());
Response.AddHeader("Content-Disposition","attachment; filename=file.pdf");
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();

Upvotes: 3

Related Questions