download file using file path stored in database in ASP.Net - asp.net

I'm using VS2012 ASP.NET website, and I have an asp.net page where I upload files to a folder.
When I upload the files, it stores the path in SQL database tabel field like ~/Client_Info/text.docx and the file itself is saved in a folder.
Now I want to download the files I have stored by displaying it in a gridview with a download link. But after a whole day searching I cannot get a answer. Can someone help me out?
protected void lnkDownload_Click(object sender, EventArgs e)
{
LinkButton lnkbtn = sender asLinkButton;
GridViewRow gvrow = lnkbtn.NamingContainer as GridViewRow;
int fileid = Convert.ToInt32(gvDetails.DataKeys[gvrow.RowIndex].Value.ToString());
string name, type;
using (SqlConnection con=new SqlConnection(strCon))
{
using (SqlCommand cmd=new SqlCommand())
{
cmd.CommandText = "select FileName, FileType, FileData from FileInformation where Id=#Id";
cmd.Parameters.AddWithValue("#id", fileid);
cmd.Connection = con;
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
if(dr.Read())
{
Response.ContentType = dr["FileType"].ToString();
Response.AddHeader("Content-Disposition",
"attachment;filename=\""
+ dr["FileName"] + "\"");
Response.BinaryWrite((byte[])dr["FileData"]);
Response.End();
}
}
}
}

In order to write a file to the Response you can use the Response.WriteFile function. It takes as a parameter the physical path of the file.
You can try the following code, assuming the file path is correct and the file exists.
Response.ContentType = dr["FileType"].ToString();
Response.AddHeader("Content-Disposition",
"attachment;filename=\""
+ dr["FileName"].ToString() + "\"");
Response.WriteFile(Server.MapPath(dr["FileName"].ToString()));
Response.End();

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 save collapsed layout of AspxPivotGrid to SQL Database?

I am using divexpress pivotgrid control.
I want to do save and restore the layout. I can do that simply by using Session.
But I don't know how to save it into my SQL Database.
This code without database
UPDATED
protected void ASPxButton1_Click(object sender, EventArgs e)
{
Session["Layout"] = ASPxPivotGrid1.SaveLayoutToString();
MemoryStream stream = new MemoryStream(byteArray);
string cs = ConfigurationManager.ConnectionStrings["HQWebMatajer13"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "INSERT INTO [HQWebMatajer].[dbo].[ReportSave]([UserID],[ReportName],[UserFileName],[ReportData])VALUES('faisal.3012','TotalSales','faisalxxx',#ReportData)";
cmd.Parameters.AddWithValue("#ReportData", stream);
con.Open();
cmd.ExecuteNonQuery();
}
//divServer.InnerHtml = Session["Layout"].ToString();
}
protected void ASPxButton2_Click(object sender, EventArgs e)
{
string text = "";
string cs = ConfigurationManager.ConnectionStrings["HQWebMatajer13"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "select reportdata from [HQWebMatajer].[dbo].[ReportSave] where UserID='faisal.3012'";
con.Open();
string xxx = cmd.ExecuteScalar().ToString();
StreamReader reader = new StreamReader(xxx);
text = reader.ReadToEnd();
}
ASPxPivotGrid1.LoadLayoutFromString(text);
}
UPDATE: Saving to database is working, but when i try to restore from database it throws the following error
System.IO.FileNotFoundException: Could not find file 'C:\Program Files (x86)\IIS Express\System.Byte[].
on this line
StreamReader reader = new StreamReader(xxx);
I don't know any idea about how to convert and where to convert. The same question asked in devexpress in this link.. They referred to this stackoverflow. But the convertion I don't understand how to make it into my scenario.
Thanks
select reportdata from [HQWebMatajer].[dbo].[ReportSave] where UserID='faisal.3012'
You check what is the output of the above line in the DB.
You may have not initialized the variable byteArray with grid data. Break code at
MemoryStream stream = new MemoryStream(byteArray);
and check what you are storing in to DB.

Move pdf file from SQL database to local ASP.net

I am trying to move the saved pdf file in my database to my local drive. I cannot find a way to do it. When I click on button1 , the dialog save or open shows up. I want to save the file directly on my local drive. Any help ?
please note that reader["FileData"] contains my file.
protected void Button1_Click(object sender, EventArgs e)
{
string id = TextBox1.Text.TrimEnd();
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Select * From FileInformation where Id=3";// +id + " ";
cmd.Connection = con;
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
reader.Read();
Response.Clear();
//Response.Buffer = true;
Response.ContentType = reader["FileType"].ToString();
Response.AddHeader("Content-Disposition", "attachment;filename=\"" + reader["FileName"] + "\"");
Response.BinaryWrite((byte[])reader["FileData"]);
Response.Flush();
Response.End();
con.Close();
}
Any help on this ?

How to save Video file in DB?

I have a task to insert Video in DB and display it by Html5 video control. I did my code well and the video saved well in DB but when I tried to play the video it doesn't and when I checked my code I found that the video saved in DB with this path ~/res/Files/. When I
removed the ~/ as the path will be res/Files/ it worked well. How can I solve this issue?
protected void btnSubmit_Click(object sender, ImageClickEventArgs e)
{
btier.AddObject("~/res/Files/" + FUFile.FileName);
FUFile.SaveAs(Server.MapPath("~/res/Files/" + FUFile.FileName));
}
The reason being, you are passing the path as a string parameter to your method AddObject and to MapPath. Hence the path will remain "~/res/..." instead of resolving to the application root.
You have to first resolve the root and then save that path. One safe option is to use VirtualPathUtility. Something like this:
tempVar = VirtualPathUtility.ToAbsolute("~/res/Files/" + FUFile.FileName);
btier.AddObject(tempVar);
FUFile.SaveAs(Server.MapPath(tempVar));
Where tempVar is a string variable.
protected void btnUpload_Click(object sender, EventArgs e)
{
using (BinaryReader br = new BinaryReader(FileUpload1.PostedFile.InputStream))
{
byte[] bytes = br.ReadBytes((int)FileUpload1.PostedFile.InputStream.Length);
string strConnString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "insert into tblFiles(Name, ContentType, Data) values (#Name, #ContentType, #Data)";
cmd.Parameters.AddWithValue("#Name", Path.GetFileName(FileUpload1.PostedFile.FileName));
cmd.Parameters.AddWithValue("#ContentType", "video/mp4");
cmd.Parameters.AddWithValue("#Data", bytes);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
Response.Redirect(Request.Url.AbsoluteUri);
}
Complete step by step tutorial:
http://www.aspsnippets.com/Articles/Upload-Save-Retrieve-and-Play-MP4-Video-files-with-live-streaming-from-Database-in-ASPNet-using-C-and-VBNet.aspx

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"]

Resources