You are on page 1of 5

FILE UPLOAD IN DATABASE using using using using using using using using using using using using

using System; System.Configuration; System.Data; System.Linq; System.Web; System.Web.Security; System.Web.UI; System.Web.UI.HtmlControls; System.Web.UI.WebControls; System.Web.UI.WebControls.WebParts; System.Xml.Linq; System.Data.SqlClient; System.IO;

public partial class _Default : System.Web.UI.Page { SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString) ; protected void Page_Load(object sender, EventArgs e) { } protected void btnUpload_Click(object sender, EventArgs e) { string filepath = FileUpload1.PostedFile.FileName; string filename = Path.GetFileName(filepath); string ext = Path.GetExtension(filename); string contenttype = String.Empty; switch (ext) { case ".doc": contenttype break; case ".docx": contenttype break; case ".xls": contenttype break; case ".xlsx": contenttype break; case ".txt": contenttype break; case ".jpg": contenttype break; case ".png": contenttype break; case ".gif":

= "application/octet-stream"; = "application/octet-stream"; = "application/octet-stream"; = "application/octet-stream"; = "application/octet-stream"; = "image/vnd.jpg"; = "image/vnd.png";

contenttype = "image/vnd.gif"; break; case ".pdf": contenttype = "application/octet-stream"; break; } if (contenttype != string.Empty) { Stream fs = FileUpload1.PostedFile.InputStream; BinaryReader br = new BinaryReader(fs); Byte[] bytes = br.ReadBytes((Int32)fs.Length); cn.Open(); //string str = "insert into Fileupload([Name],[ContentType],[Data]) values('" + filename + "','"+contenttype+"','" + bytes+ "')"; String str = "insert into Fileupload([Name],[ContentType],[Data])values(@FN,@CT,@BY)"; SqlCommand cmd = new SqlCommand(str,cn); cmd.Parameters.AddWithValue("@FN", filename); cmd.Parameters.AddWithValue("@CT", contenttype); cmd.Parameters.AddWithValue("@BY", bytes); int n1 = cmd.ExecuteNonQuery(); cn.Close(); if (n1 > 0) { Response.Write("<script>alert('File has been Uploaded Successfully');</script>"); } lblResult.Text = "File uploaded"; } else { lblResult.Text = "Error"; } } protected void lbtnDownload_Click(object sender, EventArgs e) { cn.Open(); SqlCommand cmd = new SqlCommand("select Name,ContentType,Data from Fileupload where Id = @id1", cn); cmd.Parameters.AddWithValue("@id1", txtID.Text); DataTable dt = GetData(cmd); if (dt != null) { download(dt); Response.Write("<script>alert('File has been Downloaded Successfully');</script>"); lblResult.Text = "File Downloaded"; } } private DataTable GetData(SqlCommand cmd) { DataTable dt = new DataTable();

String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["Con"].Connection String; SqlConnection con = new SqlConnection(strConnString); SqlDataAdapter sda = new SqlDataAdapter(); cmd.CommandType = CommandType.Text; cmd.Connection = con; try { con.Open(); sda.SelectCommand = cmd; sda.Fill(dt); return dt; } catch { return null; } finally { con.Close(); sda.Dispose(); con.Dispose(); } } private void download(DataTable dt) { Byte[] bytes = (Byte[])dt.Rows[0]["Data"]; Response.Buffer = true; Response.Charset = ""; Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.ContentType = dt.Rows[0]["ContentType"].ToString(); Response.AddHeader("content-disposition", "attachment;filename=" + dt.Rows[0]["Name"].ToString()); Response.BinaryWrite(bytes); Response.Flush(); Response.End(); } }

FILE UPLOAD IN FOLDER

using using using using using using using using using using using using using using

System; System.Configuration; System.Data; System.Linq; System.Web; System.Web.Security; System.Web.UI; System.Web.UI.HtmlControls; System.Web.UI.WebControls; System.Web.UI.WebControls.WebParts; System.Xml.Linq; System.Data.SqlClient; System.Net; System.IO;

public partial class _Default : System.Web.UI.Page { //SqlConnection cn = new SqlConnection("Data Source=ANANDPC\\SQLEXPRESS;Initial Catalog=Sample;Integrated Security=True"); protected void Page_Load(object sender, EventArgs e) { } protected void btnSubmit_Click(object sender, EventArgs e) { if ((File1.PostedFile != null) && (File1.PostedFile.ContentLength > 0)) { string fn = System.IO.Path.GetFileName(File1.PostedFile.FileName); //string SaveLocation = Server.MapPath("Data") + "\\" + fn; string SaveLocation ="F:\\"+fn; try { File1.PostedFile.SaveAs(SaveLocation); Response.Write("The file has been uploaded."); } catch (Exception ex) { Response.Write("Error: " + ex.Message); //Note: Exception.Message returns a detailed message that describes the current exception. //For security reasons, we do not recommend that you return Exception.Message to end users in //production environments. It would be better to return a generic error message. } } else {

Response.Write("Please select a file to upload."); } } protected void lbtnFile_Click(object sender, EventArgs e) { HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create("http://localhost:49185/Fileupload/Syllabus .doc"); HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse(); int bufferSize = 1; Response.Clear(); Response.ClearHeaders(); Response.ClearContent(); Response.AppendHeader("Content-Disposition:", "attachment; filename=Syllabus.doc"); Response.AppendHeader("Content-Length", objResponse.ContentLength.ToString()); Response.ContentType = "application/download"; byte[] byteBuffer = new byte[bufferSize + 1]; System.IO.MemoryStream memStrm = new MemoryStream(byteBuffer, true); Stream strm = objRequest.GetResponse().GetResponseStream(); byte[] bytes = new byte[bufferSize + 1]; while (strm.Read(byteBuffer, 0, byteBuffer.Length) > 0) { Response.BinaryWrite(memStrm.ToArray()); Response.Flush(); } Response.Close(); Response.End(); memStrm.Close(); memStrm.Dispose(); strm.Dispose(); } }

You might also like