Download multiple files from gridview from download button - asp.net

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.

Related

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

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.

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");
}

File upload/download failing

I'm working on a website where I need to have upload/download functionality. Upload works fine, but when I press Download Uploaded File nearly nothing happens.
//Upload
protected void btnUpload_Click(object sender, EventArgs e)
{
string filename = Path.GetFileName(fileUpload1.PostedFile.FileName);
fileUpload1.SaveAs(Server.MapPath("Files/" + filename));
con.Open();
SqlCommand cmd = new SqlCommand("insert into FilesTable(FileName,FilePath) values(#Name,#Path)", con);
cmd.Parameters.AddWithValue("#Name", filename);
cmd.Parameters.AddWithValue("#Path", "Files/" + filename);
cmd.ExecuteNonQuery();
con.Close();
BindGridviewData();
}
//Download
protected void gvDetails_SelectedIndexChanged(object sender, EventArgs e)
{
SqlCommand com = new SqlCommand("select FileName,FilePath from FilesTable where Id=#Id", con);
com.Parameters.AddWithValue("Id", gvDetails.SelectedRow.Cells[1].Text);
SqlDataReader dr = com.ExecuteReader();
if (dr.Read())
{
Response.Clear();
Response.Buffer = true;
Response.ContentType = dr["type"].ToString();
Response.AddHeader("content-disposition", "attachment;filename=" + dr["Name"].ToString());
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.BinaryWrite((byte[])dr["data"]);
Response.End();
}
}
There are few problems with your code:
Your select query only returns FileName and FilePath but you also try to retrieve type and data from database. You can add an extra column in table to store file type since your code already saves uploaded file in Files folder then you can use dr["type"]
You need to use same file path for downloading as well that you used for saving, either store absolute path or relative path in database:
// Uploading
string filePath = Server.MapPath("Files/" + filename); // Absolute path
or
string filePath = "Files/" + filename; // Relative path
...
cmd.Parameters.AddWithValue("#Path", filePath);
// Downloading
string filePath = dr["FilePath"]; // Absolute path
or
string filePath = Server.MapPath(dr["FilePath"]); // Relative path
If file gets saved in folder instead of database then read its contents as bytes for sending to client using File or FileStream etc:
// ReadAllBytes throws memory exception for large files
byte[] fileData = File.ReadAllBytes(filePath);
The select list contains FileName as column name and not just Name, replace dr["Name"] with dr["FileName"]

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();

Resources