Click here to Skip to main content
15,897,371 members
Articles / Web Development / ASP.NET
Tip/Trick

File Upload and Download in ASP.NET

Rate me:
Please Sign up or sign in to vote.
3.31/5 (21 votes)
5 May 2011CPOL 121.9K   16   9
ASP.NET sample code for uploading and downloading files
There are lots of situation, Where we have to use file uploader in our project. But beginners don’t get proper code for Uploading and Downloading File. Using this code they can do it:

File Upload Code



C#
string FilePath = "";
string[] a = new string[1];
string fileName = "";
string FullName = "";

if (FileUploader.FileName.Length > 0)
{
     a = FileUploader.FileName.Split('.');
     fileName = Convert.ToString(System.DateTime.Now.Ticks) + "." + a.GetValue(1).ToString();
     FilePath = Server.MapPath(@"~\SavedFolder");
     Fup1.SaveAs(FilePath + @"\" + fileName);

     FullName = FilePath + @"\" + fileName;
     // Database Saved Code
}

File Download Code


C#
string filename = "filename from Database";
Response.ContentType = "application/octet-stream";
Response.AppendHeader("Content-Disposition", "attachment;filename=" + filename);
string aaa = Server.MapPath("~/SavedFolder/" + filename);
Response.TransmitFile(Server.MapPath("~/SavedFolder/" + filename));
Response.End();

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer India
India India
http://devcorners.com/
Total DotNet/Programming Solution

I am Prasanta Banerjee. I am an Asp.Net Developer. My site: http://devcorners.com/
Email: prasanta.it@hotmail.com
If any body wants to prepare for interview http://guru-code.blogspot.com/ is the good site.

Comments and Discussions

 
BugDownload code not working Pin
_Dhull 29-Jan-14 21:57
_Dhull 29-Jan-14 21:57 
Questionin case of .xls and in firefox this is not working Pin
V1CT0R.15-Dec-13 23:05
V1CT0R.15-Dec-13 23:05 
Questionhow to download uploaded file Pin
manikantaer12-Jul-12 18:35
manikantaer12-Jul-12 18:35 
my file upload code is like this:
********************************
protected void btn_submit_Click(object sender, EventArgs e)
{


SqlCommand cmd3 = new SqlCommand();
if (con.State == ConnectionState.Closed)
{
con.Open();
}
cmd3.Connection = con;
cmd3.CommandType = CommandType.StoredProcedure;
cmd3.CommandText = "sp_www_ca";
cmd3.Parameters.AddWithValue("@refno", rid);
cmd3.Parameters.AddWithValue("@ca_refno", hdn_ca_refno.Value);
cmd3.Parameters.AddWithValue("@editca", txt_edit_ca.Text);

if (fileUpload1.PostedFile.ContentLength > 0 && fileUpload1.PostedFile.FileName != null)
{
string filename = Path.GetFileName(fileUpload1.PostedFile.FileName);
fileUpload1.SaveAs(Server.MapPath("~/Files/" + filename));
cmd3.Parameters.AddWithValue("@Name1", filename);
cmd3.Parameters.AddWithValue("@Path1", filename);

}
else
{
cmd3.Parameters.AddWithValue("@Name1", "");
cmd3.Parameters.AddWithValue("@Path1", "");
}


cmd3.ExecuteNonQuery();
Response.Redirect("~/www/www_caedit_success.aspx?ca_refno=" + hdn_ca_refno.Value);

}
file stored in DB like this
***************************

filename1 filepath1
75-U7-A0004.doc 75-U7-A0004.doc
my file download code like this
*******************************
string doc = dr["filepath1"].ToString();

HyperLink1.NavigateUrl = doc;

protected void Page_Load(object sender, EventArgs e)
{
rid = Request.QueryString["rno"].ToString();
con.ConnectionString = ConfigurationManager.AppSettings["Connection"];
con2.ConnectionString = ConfigurationManager.AppSettings["Connection"];
if (!IsPostBack)
{
con.Open();
con2.Open();

cmd = new SqlCommand("select empname,ticketno,date,time1,asobsrin,obname,obnumber,function1,isrel1,isrel2,processdoc,processrefno,narrate,ca_edit,filepath1 from kecbliss.dbo.www_add_details where ca_refno='" + rid + "'", con);
dr = cmd.ExecuteReader();
while (dr.Read())
{
lbl_name.Text = dr["empname"].ToString();
lbl_tokenno.Text = dr["ticketno"].ToString();
lbl_date.Text = dr["date"].ToString();
lbl_time.Text = dr["time1"].ToString();
lbl_observe.Text = dr["asobsrin"].ToString();
obsrv = lbl_observe.Text;

lbl_function.Text = dr["function1"].ToString();
lbl_relate.Text = dr["isrel1"].ToString();
lbl_relate2.Text = dr["isrel2"].ToString();
lbl_procdoc.Text = dr["processdoc"].ToString();
lbl_proc_ref.Text = dr["processrefno"].ToString();
lbl_narrate.Text = dr["narrate"].ToString();
lbl_narrate_edit.Text = dr["ca_edit"].ToString();
string doc = dr["filepath1"].ToString();

HyperLink1.NavigateUrl = doc;
}
if (obsrv == "With Other")
{
SqlCommand cmd2 = new SqlCommand("select obname,obnumber from kecbliss.dbo.www_add_details where refno='" + rid + "'", con2);
SqlDataAdapter da = new SqlDataAdapter(cmd2);
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}


}
}

when i click view hyperlink i am getting error like this
*******
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.

Requested URL: /bliss/www/75-U7-A0004.doc
****
off course requested URL must show like this /bliss/Files/75-U7-A0004.doc


give me solution for this
Generalcan this code be used to download any kind of file Pin
ashishmaniyar13-Nov-11 19:06
ashishmaniyar13-Nov-11 19:06 
Generalchange code line Pin
zSegundo2-May-11 13:29
zSegundo2-May-11 13:29 
Generalur code for file download Pin
Himil Modi26-Apr-11 19:47
Himil Modi26-Apr-11 19:47 
Answer code for file download from server Pin
Debasis hota-Dot Net Devloper28-Aug-13 5:29
Debasis hota-Dot Net Devloper28-Aug-13 5:29 
GeneralWhat happens if... Pin
Henry Minute24-Apr-11 11:31
Henry Minute24-Apr-11 11:31 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.