December 16, 2010

File Upload & Download with asp.net, C# & sql server

Files of ms-word, ms-excel, pdf and images are stored (Uploaded)  into sql server 2005 and retrieving back to client side(downloaded to client system).
Iam saving the files in database in binary format & list of files is listed in dropdown fetched from sql server.
. 1. Create a Table in database in which we are going store our uploaded files, 
CREATE TABLE [dbo].[Files](
    [FileID] [int] NOT NULL,
    [FileName] [varchar](50) NOT NULL,
    [Files] [varbinary](max) NOT NULL
) ON [PRIMARY]

2.Create the  Fileupload.aspx which contains
  • ·         FileUpload control
  • ·         Dropdownlist
  • ·         Buttons(2)-Upload, Open

  Fileupload.aspx
Select the File to upload
        <asp:FileUpload ID="FileUpload1" runat="server" />
        <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Upload" />
Download or Open the File<asp:DropDownList ID="DropDownList1" runat="server"></asp:DropDownList>
        <asp:Button ID="Button2" runat="server" onclick="Button2_Click" Text="Open" />

3.The code for code behind of Fileupload.aspx.cs as fallows

protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                Filldrop(); 
            }
        }
        private void Filldrop()
    {
        SqlDataAdapter ad = new SqlDataAdapter("Select FileID, FileName from files", "Data Source=servername;Initial Catalog=databasename");
            DataSet ds=new DataSet() ;
            ad.Fill(ds, "docs");
            DropDownList1.DataSource = ds.Tables[0];
            DropDownList1.DataTextField = " FileName ";
            DropDownList1.DataValueField = " FileName ";
            DropDownList1.DataBind();
    }
protected void Button1_Click(object sender, EventArgs e)
        {
            try
            {
                if (FileUpload1.HasFile)
                {
                    int filsize = FileUpload1.PostedFile.ContentLength;
                    byte[] filebyt = new byte[filsize];
                    FileUpload1.PostedFile.InputStream.Read(filebyt, 0, filsize);
                    SqlConnection con = new SqlConnection("Data Source=servername;Initial Catalog=databasename");
                    SqlCommand cmd = new SqlCommand("insert into files(FileName, Files)"+
                        "values (@FileName,@ Files)", con);
                    cmd.Parameters.AddWithValue("@FileName ", Path.GetFileName(FileUpload1.PostedFile.FileName));
                    cmd.Parameters.AddWithValue("@Files ", filebyt);
                    con.Open();
                    int result = cmd.ExecuteNonQuery();
                    con.Close(); cmd.Dispose(); con.Dispose(); filebyt = null;
                    Response.Write("File uploaded");
                }
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }
protected void Button2_Click(object sender, EventArgs e)
        {
            try
            {
                string strname = string.Empty;
                string namee = DropDownList1.SelectedItem.Value;
                SqlConnection con = new SqlConnection("Data Source=servername;Initial Catalog=databasename");
                SqlCommand cmd = new SqlCommand("select FileName, Files from files where names='"+namee+"'", con);
                con.Open();
                SqlDataReader dr = cmd.ExecuteReader();
                while (dr.Read())
                {
                    strname = dr["FileName "].ToString();
                    Byte[] filbyt = (Byte[])dr["Files "];
                    FileStream filstr = new FileStream(
                        Server.MapPath("Documents")
                        + @"\" + strname, FileMode.OpenOrCreate);
                    filstr.Write(filbyt, 0, filbyt.Length);
                    filstr.Close(); filstr.Dispose();
                    filbyt = null;
                }
con.Close(); cmd.Dispose(); con.Dispose();
                if (strname != string.Empty)
                {
Response.Redirect(@"Documents/" + strname);
                }
            }
            catch (Exception ex)
            {
               Response.Write(ex.Message);
            }
}

4. Now the Project executes perfectly….

Fallow me to play interesting codes with c#, asp.net coding

No comments:

Post a Comment