I have a String variable (in C#) that contain the full path of PDF file on my server
(like that "~/doc/help.pdf").
I want that in click on button, this file will download to the client computer.
I created a button and made onClick event in C#. Now, which code should I write to do that?
I think you are looking for something like this.
private void Button1_click(object sender, System.EventArgs e)
{
Response.ContentType = "Application/pdf";
Response.AppendHeader("Content-Disposition", "attachment; filename=help.pdf");
Response.TransmitFile(Server.MapPath("~/doc/help.pdf"));
Response.End();
}
Try this code on your btn_Click
:
Response.Redirect("~/doc/link.pdf");
I would suggest the following to be placed into your button click event code.
This will provide the user with a popup to download the file. I've tested it thoroughly and use it in production code.
void btnDownloadFile_Click(object sender, EventArgs e)
{
string strLocalFilePath = "~/doc/help.pdf";
string fileName = "help.pdf";
Response.Clear();
Stream iStream = null;
const int bufferSize = 64 * 1024;
byte[] buffer = new Byte[bufferSize];
int length;
long dataToRead;
try
{
iStream = new FileStream(strLocalFilePath, FileMode.Open, FileAccess.Read, FileShare.Read);
dataToRead = iStream.Length;
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
while (dataToRead > 0)
{
if (Response.IsClientConnected)
{
length = iStream.Read(buffer, 0, bufferSize);
Response.OutputStream.Write(buffer, 0, length);
Response.Flush();
buffer = new byte[bufferSize];
dataToRead = dataToRead - length;
}
else
{
//prevent infinate loop on disconnect
dataToRead = -1;
}
}
}
catch (Exception ex)
{
//Your exception handling here
}
finally
{
if (iStream != null)
{
iStream.Close();
}
Response.Close();
}
}
With an ASP button:
button.OnClientClick = string.Format("javascript:window.location='{0}'", pdfLink);
The logic behind this is here: Client-side click
This will not reload the page and do a post-back, it will just navigate to the PDF which will be displayed in the browser.
Set the button's onclick event to this scriptlet:
onclick="javascript:window.location='/doc/help.pdf'"
To create that server-side:
<input type="button" onclick="javascript:window.location='<%=PDFLink %>'" />
Where PDFLink is a string property in the code behind:
public string PDFLink
{
get
{
return "/doc/link.pdf";
}
}
From here it should be trivial to take the string from the database and render it absolute if need be.
Response.ContentType = "Application/pdf";
Response.AppendHeader("Content-Disposition", "attachment; filename=File_Name.pdf");
Response.TransmitFile(Server.MapPath("Folder_Name/File_Name.pdf"));
Response.End();