Monday 6 February 2012

Multiple fileuploder with sql server in asp.net


Introduction
The multiple fileuploader is important in the web site. When you are create a new website you have to implement in the in the picture galary inside the album as well. So in this article I will explain how to we can upload multiple file with a single click.
Implementation
As usual create a simple asp.net web project and then add following html code to design page accept the user input such as button to add file uploder according to your need and upload button for save image inside the folder and the database. and create a folder named in the root of your application where the images will be stored.

 
Figure:multiple fileuploders
HTML Code
<head runat="server">
    <title>Multiple FileUpload Example</title>
    <%--i am using this javascript function to add the fileuploader --%>
    <script type = "text/javascript">
        var counter = 0;
        function AddFileUpload()
        {
             var div = document.createElement('DIV');
             div.innerHTML = '<input id="file' + counter + '" name = "file' + counter + '" type="file" /><input id="Button' + counter + '" type="button" value="Remove" onclick = "RemoveFileUpload(this)" />';
             document.getElementById("FileUploadContainer").appendChild(div);
             counter++;
        }
        function RemoveFileUpload(div)
        {
             document.getElementById("FileUploadContainer").removeChild(div.parentNode);
        }
    </script>
</head>
<body>
    <form id="form1" runat="server" enctype="multipart/form-data" method = "post">
        <span style ="font-family:Arial">Click to add files</span>&nbsp;&nbsp;
         <!--FileUpload Controls will be added here after clicking below button -->
         <!--m calling AddFileUpload() function on the click of this button  -->
        <input id="Button1" type="button" value="add" onclick = "AddFileUpload()" />
       
        <br /><br />
        <div id = "FileUploadContainer">
            <!--FileUpload Controls will be added here -->
        </div>
        <br />
      <!--this button is used to upload the files and save inside the database -->
        <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" />
    </form>
</body>
</html>
 We have designed galary page, to upload the multiple picture like as facebook and orkut.
now write code for multiple fileuploader.
C# code
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
 // this  nemaespace for file upload.
using System.IO;

using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection();
    SqlCommand cmd = new SqlCommand();
    // here m declared some variables that will be used to store the file name
    string fn, aguid;
    protected void Page_Load(object sender, EventArgs e)
    {
        // here i am creating connection with the database
        //or
        //  here i am declaring  connectionstring
        con = new SqlConnection(ConfigurationManager.ConnectionStrings["cnn"].ConnectionString);
        con.Open();
       

    }
    protected void btnUpload_Click(object sender, EventArgs e)
    {
        // here m using for loop
        // Request.Files.Count(with this line  i am count how many files user want to upload)
        // and this loop will work(i depend on the Request.Files.Count )
      
        for (int i = 0; i < Request.Files.Count; i++)
        {
            HttpPostedFile PostedFile = Request.Files[i];
            // here m checking that, fileuploader have file or not
            // if yes then it will go inside the if condition
            if (PostedFile.ContentLength > 0)
            {
                // here m opening the connection if the connection will close
                if (con.State == ConnectionState.Closed)
                {
                    con.Open();
                }
               // in the fn variable m storing file
                fn = System.IO.Path.GetFileName(PostedFile.FileName);
                // here m using Guid.NewGuid()  method to create file new name
                aguid = Guid.NewGuid() + fn.Substring(fn.LastIndexOf(".")).ToString();
                // here m storing the file inside the folder
                PostedFile.SaveAs(Server.MapPath("image_thumbnail\\") + aguid);
                // here m using simple  insertion code
                 SqlCommand cmd = new SqlCommand();
                // insert query
                cmd.CommandText = @"INSERT INTO  tb_image_upload
                VALUES(@image_upload)";
                cmd.Connection = con;
                // here m a passing parameter
                cmd.Parameters.AddWithValue("@image_upload", aguid);
                cmd.ExecuteNonQuery();
                cmd.Dispose();
                con.Close();
               
             
            }
           
        }
    }
}

In above code, just create multiple file uploader in asp.net using c#.

Sql server script:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[tb_image_upload]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[tb_image_upload](
      [id] [bigint] IDENTITY(1,1) NOT NULL,
      [image_upload] [nvarchar](500) NULL,
 CONSTRAINT [PK_tb_image_upload] PRIMARY KEY CLUSTERED
(
      [id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END


Conclusion
Through this article, you have learned how to ‘upload multiple files with a single click’ operation in web site using asp.net. ok guys(developers) enjoy the code.

5 comments:

  1. Hello,
    Do you have this Demo for Download?

    ReplyDelete
    Replies
    1. Hi!! person i have no demo for download. You can copy and paste to execute this code.

      Thankx..

      Delete
  2. How can i open this uploaded documents. Please send me code

    ReplyDelete
  3. hi
    cant insert to sql can you help me???

    ReplyDelete
    Replies
    1. Hello Sarkaut. Please tell me about the problem which you facing at the insertion time.

      Thanks
      Using asp.net

      Delete