How to download pdf file from database using asp gridview link button - asp.net

I have stored binary data into a db.
When I'm fetching and trying to download same pdf file I'm unable to do it.
Below is my code snippet:
protected void grdDownload_Command(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Download")
{
int index = Convert.ToInt32(e.CommandArgument);
DataTable dtFilterData = `enter code here`GetPDFFile("D", Convert.ToString(index));
Response.Clear();
Response.Buffer = true;
Response.ContentType = dtFilterData.Rows[0]["ContentType"].ToString();
Response.AddHeader("content-disposition", "attachment;filename=" + dtFilterData.Rows[0]["Name_File"].ToString()); // to open file prompt Box open or Save file
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.BinaryWrite((byte[])dtFilterData.Rows[0]["FileData"]);
Response.End();
}
}

Finally i have resolved this issue. We need to add update panel for link button inside the Item template.
Adding Postback Trigger has resolved this issue.

Related

Download multiple files from gridview from download button

I am saving the path of the file in database and file is in server folder and the gridview control is used to show the files from the database. i need to download the selective files from the gridview using download button Click event.
Here is my code:
protected void btn_download_Click(object sender, EventArgs e)
{
using (ZipFile zip = new ZipFile())
{
zip.AlternateEncodingUsage = ZipOption.AsNecessary;
zip.AddDirectoryByName("records");
foreach (GridViewRow row in GridView1.Rows)
{
if ((row.FindControl("chkSelectoptn") as CheckBox).Checked)
{
string filePath = (row.FindControl("lblFilePath") as Label).Text;
zip.AddFile(filePath, "records");
}
}
Response.Clear();
Response.BufferOutput = true;
string zipName = String.Format("Zip_{0}.zip", DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"));
Response.ContentType = "application/zip";
Response.AddHeader("content-disposition", "attachment; filename=" + zipName);
zip.Save(Response.OutputStream);
Response.End();
}
}
I am using a label lblFilePath to give the path of the file name which we had store in the database.
But "FileNotFoundException" occurs.
Please suggest.

How to let user select the location for downloading a file in asp.net?? To be precise a open file dialog equivalent in asp(Not fileUpload)

I am downloading a pdf file in my project. I want to let the user decide where to download the File. Quick help is helpful.
Thanks
try this:
It will display a dialog box in the browser and the user will select on where to save the file
protected void DownloadFile_Click(object sender, EventArgs e)
{
String Filepath;
System.IO.FileInfo file = new System.IO.FileInfo(Filepath); // full file path on disk
Response.ClearContent(); // Clear previous content
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/pdf";
Response.TransmitFile(file.FullName);
Response.End();
}
You haven't specified how your application is serving this PDF file, but assuming that you have some WebForm which is streaming it to the Response, you should set the Content-Disposition header as attachment in order to force the Save As dialog in the browser.
For example:
protected void Download(object sender, EventArgs e)
{
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment; filename=example.pdf");
Response.WriteFile(#"c:\work\example.pdf");
}

how to create a hyperlink for file download in asp.net?

I have some files stored on my machine. When a user wants to generate a link the page should generate a hyperlink. This hyperlink can be used by any other user so as to download the file
Have a LinkButton and for the click event do the following
your aspx file will have the following
<asp:LinkButton runat="server" OnClick="btnDownload_Click" Text="Download"/>
Your code behind will have the following
protected void btnDownload_Click(object sender, EventArgs e)
{
try
{
var fileInBytes = Encoding.UTF8.GetBytes("Your file text");
using (var stream = new MemoryStream(fileInBytes))
{
long dataLengthToRead = stream.Length;
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.BufferOutput = true;
Response.ContentType = "text/xml"; /// if it is text or xml
Response.AddHeader("Content-Disposition", "attachment; filename=" + "yourfilename");
Response.AddHeader("Content-Length", dataLengthToRead.ToString());
stream.WriteTo(Response.OutputStream);
Response.Flush();
Response.Close();
}
Response.End();
}
}
catch (Exception)
{
}
}
you can direct link the hyperlink with the file if you know the address but this is limited by the browser. eg. if pdf reader is installed on the client then the pdf will not be downloaded instead it will be shown. A good solution would be to have a seperate page for downloading files. just pass filename in querystring and in the pageload event just outpit the file in response stream.This way you can use url say dwnld.aspx?filename.ext
Now you can generate urls via the above logic.

Download a string as a file in ASP.NET

The following method, based on code in this question, shows a file download dialog box in the browser, but then the download never starts (it stays at 0%):
protected void lnkExport_Click(object sender, EventArgs e) {
var bytes = Encoding.ASCII.GetBytes(SelectRecords()); //Data to be downloaded
Response.Clear();
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "attachment; filename=\"test.xls\"");
using (var stream = new MemoryStream(bytes)) {
Response.AddHeader("Content-Length", stream.Length.ToString());
stream.WriteTo(Response.OutputStream);
}
}
Any idea what's up?
Your code worked fine for me but you may want to try adding this as the last line of your click handler:
Response.End();

How to export GridView to excelsheet?

I have a gridview in my page. What I want is when user clicks on the button "Export", it should open a box to download a file and save as a excel sheet. I have pagging enabled in my grid but when I export data, all rows must be sent in the excel sheet irrespective of pagging. I can not export my data source(datatable) because it contains few other columns which are hidden but I am using it just for my purpose and dont what to show it to the users.
How can I do so....??? I am not getting any Idea...
As James Johnson said..I did like that. This is the code given by him
protected void btnExport_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/vnd.ms-excel";
Response.Charset = "";
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
GridView1.RenderControl(oHtmlTextWriter);//Error is thrown from here.
Response.Write(oStringWriter.ToString());
Response.End();
}
But doing this throws following error at from at specified potion in code
Control 'ctl00_ContentPlaceHolder1_ViewAdvances1_grdAdvance' of type 'GridView' must be placed inside a form tag with runat=server.
I have placed gridview in usercontrol, the usercontrol is placed in .aspx page and that page uses master page which already have form tag.
You can try something like this:
protected void btnExport_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/vnd.ms-excel";
Response.Charset = "";
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
GridView1.RenderControl(oHtmlTextWriter);
Response.Write(oStringWriter.ToString());
Response.End();
}
It's a lot of discussions regarding this:
export gridview rows to excel sheet
Export GridView to Excel
Export gridview into excel in Windowsformsapplication (maybe some useful info you will find here)
Add the following code to your code behind:
Public Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)
'dont delete - needed for excel export
End Sub
I got the solution for export to excel in master page.
put this code after page load code
public override void VerifyRenderingInServerForm(Control control)<br/>
{<br/>
/* Verifies that the control is rendered */<br/>
//base.VerifyRenderingInServerForm(control);
}
then
protected void btnExportExcel_Click(object sender, EventArgs e)<br/>
{<br/>
try<br/>
{<br/>
BindReportdata(ddlReport.SelectedIndex);<br/>
Response.Clear();<br/>
Response.Buffer = true;<br/>
Response.AddHeader("content-disposition",<br/>
"attachment;filename=report.xls");<br/>
Response.ContentType = "application/ms-excel";<br/>
StringWriter sw = new StringWriter();<br/>
HtmlTextWriter hw = new HtmlTextWriter(sw);<br/>
for (int i = 0; i < gv_ReportData.Rows.Count; i++)<br/>
{
GridViewRow row = gv_ReportData.Rows[i];<br/>
}
gv_ReportData.GridLines = GridLines.Both;<br/>
gv_ReportData.RenderControl(hw);<br/>
Response.Write(sw.ToString());<br/>
Response.Flush();<br/>
Response.End();<br/>
}<br/>
catch (Exception ex)<br/>
{<br/>
throw ex;<br/>
}<br/>
}<br/>
and in aspx page use updatepanel and trigger for button

Resources