Reputation: 21
I have used a Gridview Control to display the contents of a directory in asp.net webforms.
The contents are filtered to display only PDF files.
I also have a Button inside a TemplateField. On the click of the button the user should be able to download and save the PDF file.
The columns displayed in the Gridview are File Name, Modified Date and Size.
How can I program the Button click to download and save the PDF file?
Upvotes: 0
Views: 14227
Reputation: 227
Hi I use Gridview as well.
This is the code I use:
protected void DownloadFile(object sender, EventArgs e)
{
string filePath = (sender as LinkButton).CommandArgument;
Response.ContentType = ContentType;
Response.AppendHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(filePath));
Response.ContentType = "application/pdf";
Response.WriteFile(filePath);
Response.End();
}
In the GridView you can have something like this:
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkDownload" Text="Download" CommandArgument='<%# Eval("Value") %>' runat="server" OnClick="DownloadFile"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
Upvotes: 0
Reputation: 3571
In your Button
click event, write the following code.
protected void Button1_Click(object sender, EventArgs e)
{
Response.ContentType = "Application/pdf";
Response.AppendHeader("Content-Disposition", "attachment; filename=Your_Pdf_File.pdf");
Response.TransmitFile(Server.MapPath("~/Files/Your_Pdf_File.pdf"));
Response.End();
}
Upvotes: 0
Reputation: 8087
I have a function that performs a file download.
public static void DownloadFile(string FilePath, System.Web.HttpResponse response)
{
System.IO.FileInfo file = new System.IO.FileInfo(FilePath);
if ((file.Exists))
{
response.Clear();
response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
response.AddHeader("Content-Length", file.Length.ToString());
response.ContentType = "application/octet-stream";
response.WriteFile(file.FullName);
response.End();
response.Close();
file = null;
}
}
The FilePath
parameter is the physical path, so if you have the virtual path (e.g. ~/Folder/file.pdf
) might need to use the Server.MapPath(...)
function to call the function.
Upvotes: 0