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"]
Related
Can anyone tell me how can I create a pdf file using iTextSharp 7 and popup a save dialog instead of saving it to a specific disk location?
My test code is the following:
protected void btnPrint_OnClick(object sender, EventArgs e)
{
Document doc = new Document(PageSize.A4, 25f, 20f, 20f, 10f);
var output = new FileStream(Server.MapPath("MyFirstPDF.pdf"), FileMode.Create);
var writer = PdfWriter.GetInstance(doc, output);
doc.Open();
doc.Add(new Paragraph("test!"));
doc.Close();
}
The workaround I found is the following:
After creating the document:
string path = "C:\\...";
string fileName = "PdfFile.pdf";
FileInfo fileInfo = new FileInfo(path);
Byte[] FileBuffer = File.ReadAllBytes(fileInfo.FullName);
if (FileBuffer != null)
{
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
Response.AddHeader("content-length", FileBuffer.Length.ToString());
Response.BinaryWrite(FileBuffer);
Response.Flush();
//DELETE FILE AFTER DOWNLOAD
fileInfo.Delete();
Response.End();
}
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.
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();
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 ?
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