Monday, 17 March 2014

Drag & drop to upload multiple files using AjaxFileUpload like Facebook in asp.net

Drag & drop to upload multiple files using AjaxFileUpload like Facebook in asp.net

Introduction: In previous articles i explained How to Get city, state and country based on zip code using Google map API in asp.net and Ajax AutoCompleteExtender control example using web service and How to upload file and create Zip file in asp.net and How to check and validate file extension before uploading a file through FileUpload control and How to upload, download and delete files from GridView

AjaxFileUpload control example to upload multiple files by Drag and Drop using Ajax in asp.net
Click on image to enlarge
In this article I am going to explain How to upload multiple files/images by drag and  drop or by browsing/selecting like Facebook using AjaxFileUpload control of AJAX in asp.net. We will create an asp.net application having the functionality of uploading multiple images to create album and saving the path of each image in table of SqlServer database. Then Uploaded images will be  binded to DataList data  control to show as album.

Implementation: Create the Database in sql server e.g. "MyDataBase" and design the table in that database  as shown below and name it “TB_IMG”

Column
Data Type
IMAGE_ID
int(Primary Key i.e. Set identity property=true)
IMAGE_NAME
varchar(200)
IMAGE_PATH
varchar(500)

  • Now in web.config file add the connectionstring under <configuration> tag
<connectionStrings>
    <add name="conStr" connectionString="Data Source=LocalServer;Initial Catalog=MyDataBase;Integrated Security=True"/>
  </connectionStrings>

Note: Replace the Data Source ans Initial Catalog as per your application.
  •  In the design page (.aspx) place a ScriptManager control from the AJAX Extensions category of Visual studio toolbox.
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
Place AjaxFileUpload control from the Ajax Control Toolkit. For this you need to install Ajax control toolkit to use any Ajax control like AjaxFileUpload control. If you have not installed or don’t know how to install Ajax Control Toolkit then read my article "How to install Ajax Control Toolkit in Visual Studio?"
Also place a button control to show the album and create a  folder in root directory and name it Album
<asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <fieldset style="width:600px;">
            <legend>AjaxFileUpload control example to upload multiple files by Drag and Drop</legend>
              <table style="width:100%;">
                  <tr>
                      <td width="20%">Upload Album</td>
                      <td>
                          <asp:AjaxFileUpload ID="AjaxFileUpload1" runat="server"                          
                           onuploadcomplete="AjaxFileUpload1_UploadComplete"/>                      
                      </td>                     
                  </tr>
                  <tr><td colspan="2">
                        <asp:DataList ID="dlImages" runat="server" RepeatColumns="4"
                    RepeatDirection="Horizontal" BackColor="White" BorderColor="#999999" BorderStyle="None" BorderWidth="1px" CellPadding="3">                
                            <AlternatingItemStyle BackColor="#DCDCDC" />
                            <FooterStyle BackColor="#CCCCCC" ForeColor="Black" />
                            <HeaderStyle BackColor="#000084" Font-Bold="True" ForeColor="White" />
                            <ItemStyle BackColor="#EEEEEE" ForeColor="Black" />
                <ItemTemplate>
                <table  border="0" style="border-bottom-color:#60BAEA;border-top-color:#60BAEA;border-left-color:#60BAEA;border-left-color:#60BAEA;" cellspacing="5"
                            >
                            <tr>
                            <td align="center">
                             <asp:Image  ID="img" runat="server" align="center" BorderStyle="Solid" BorderColor="#e0ddd7" BorderWidth="2" Height="150" ImageUrl='<%# DataBinder.Eval(Container.DataItem, "IMAGE_PATH") %>'
                                        Width="150px" />
                            </td>
                            </tr>                  
                     </table>
                </ItemTemplate>                   
                            <SelectedItemStyle BackColor="#008A8C" Font-Bold="True" ForeColor="White" />
                </asp:DataList>                 
              </table> 
        <center><asp:Button ID="btnViewAlbum" runat="server" Text="View Album" OnClick="btnViewAlbum_Click" />    </center>
        </fieldset>
  • Have you noticed the line <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %> added automatically next to the very first line in the design page. Actually it registers the Ajax Control on placing AjaxFileUpload control on design page.

C#.Net Code to upload multiple files by drag and drop using AjaxFileUpload control
First include following namespaces:
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
Then write the code on UploadComplete event of AjaxFileUpload control as:

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString);
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            BindAlbumDataList();
        }
    }
    protected void AjaxFileUpload1_UploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
    {
        string filePath = string.Empty;
        try
        {
            filePath = (Server.MapPath("~/Album/") + Guid.NewGuid() + System.IO.Path.GetFileName(e.FileName));
            AjaxFileUpload1.SaveAs(filePath);
            string strFile = filePath.Substring(filePath.LastIndexOf("\\"));
            string strFileName = strFile.Remove(0, 1);
            string strFilePath = "~/Album/" + strFileName;
            SqlCommand cmd = new SqlCommand("Insert into TB_IMG (IMAGE_NAME,IMAGE_PATH) values (@IMAGE_NAME,@IMAGE_PATH)", con);
            cmd.Parameters.AddWithValue("@IMAGE_NAME", strFileName);
            cmd.Parameters.AddWithValue("@IMAGE_PATH", strFilePath);
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
            cmd.Dispose();           
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message.ToString());
        }      
    }
    protected void BindAlbumDataList()
    {             
        try
        {
            SqlCommand cmd = new SqlCommand("SELECT IMAGE_NAME,IMAGE_PATH FROM TB_IMG", con);
            con.Open();
            SqlDataReader dr = cmd.ExecuteReader();
            if (dr.HasRows)
            {
                dlImages.DataSource = dr;
                dlImages.DataBind();
            }
            else
            {
                dlImages.DataSource = null;
                dlImages.DataBind();
            }
        }
        catch (Exception ex)
        {
            Response.Write("Error Occured: " + ex.ToString());
        }
        finally
        {
            con.Close();
        }    
    }   
    protected void btnViewAlbum_Click(object sender, EventArgs e)
    {
        BindAlbumDataList();
    }


Note: I have used Guid.NewGuid() to generate unique name for each image/file. GUID means Gloabally Unique Identifier.


VB.Net Code to upload multiple files by drag and drop using AjaxFileUpload control

<asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <fieldset style="width:600px;">
            <legend>AjaxFileUpload control example to upload multiple files by Drag and Drop</legend>
              <table style="width:100%;">
                  <tr>
                      <td width="20%">Upload Album</td>
                      <td>
                          <asp:AjaxFileUpload ID="AjaxFileUpload1" runat="server"/>                      
                      </td>                     
                  </tr>
                  <tr><td colspan="2">
                        <asp:DataList ID="dlImages" runat="server" RepeatColumns="4"
                    RepeatDirection="Horizontal" BackColor="White" BorderColor="#999999" BorderStyle="None" BorderWidth="1px" CellPadding="3">                
                            <AlternatingItemStyle BackColor="#DCDCDC" />
                            <FooterStyle BackColor="#CCCCCC" ForeColor="Black" />
                            <HeaderStyle BackColor="#000084" Font-Bold="True" ForeColor="White" />
                            <ItemStyle BackColor="#EEEEEE" ForeColor="Black" />
                <ItemTemplate>
                <table  border="0" style="border-bottom-color:#60BAEA;border-top-color:#60BAEA;border-left-color:#60BAEA;border-left-color:#60BAEA;" cellspacing="5"
                            >
                            <tr>
                            <td align="center">
                             <asp:Image  ID="img" runat="server" align="center" BorderStyle="Solid" BorderColor="#e0ddd7" BorderWidth="2" Height="150" ImageUrl='<%# DataBinder.Eval(Container.DataItem, "IMAGE_PATH") %>'
                                        Width="150px"  />
                            </td>
                            </tr>                   
                     </table>
                </ItemTemplate>                   
                            <SelectedItemStyle BackColor="#008A8C" Font-Bold="True" ForeColor="White" />
                </asp:DataList>                 
              </table> 
        <center><asp:Button ID="btnViewAlbum" runat="server" Text="View Album"/>    </center>
        </fieldset>

First include following namespaces:

Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Imports AjaxControlToolkit

Then write the code on UploadComplete event of AjaxFileUpload control as:

Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("conStr").ConnectionString)
    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then
            BindAlbumDataList()
        End If
    End Sub
    Protected Sub AjaxFileUpload1_UploadComplete(sender As Object, e As AjaxFileUploadEventArgs) Handles AjaxFileUpload1.UploadComplete
        Dim filePath As String = String.Empty
        Try
            filePath = (Server.MapPath("~/Album/") & Convert.ToString(Guid.NewGuid()) & System.IO.Path.GetFileName(e.FileName))
            AjaxFileUpload1.SaveAs(filePath)
            Dim strFile As String = filePath.Substring(filePath.LastIndexOf("\"))
            Dim strFileName As String = strFile.Remove(0, 1)
            Dim strFilePath As String = "~/Album/" & strFileName
            Dim cmd As New SqlCommand("Insert into TB_IMG (IMAGE_NAME,IMAGE_PATH) values (@IMAGE_NAME,@IMAGE_PATH)", con)
            cmd.Parameters.AddWithValue("@IMAGE_NAME", strFileName)
            cmd.Parameters.AddWithValue("@IMAGE_PATH", strFilePath)
            con.Open()
            cmd.ExecuteNonQuery()
            con.Close()
            cmd.Dispose()
        Catch ex As Exception
            Response.Write(ex.Message.ToString())
        End Try
    End Sub
    Protected Sub BindAlbumDataList()
        Try
            Dim cmd As New SqlCommand("SELECT IMAGE_NAME,IMAGE_PATH FROM TB_IMG", con)
            con.Open()
            Dim dr As SqlDataReader = cmd.ExecuteReader()
            If dr.HasRows Then
                dlImages.DataSource = dr
                dlImages.DataBind()
            Else
                dlImages.DataSource = dr
                dlImages.DataBind()
            End If
        Catch ex As Exception
            Response.Write("Error Occured: " + ex.ToString())
        Finally
            con.Close()
        End Try
    End Sub
  
    Protected Sub btnViewAlbum_Click(sender As Object, e As EventArgs) Handles btnViewAlbum.Click
        BindAlbumDataList()
    End Sub

Note: I have used Guid.NewGuid() to generate unique name for each image/file. GUID means Gloabally Unique Identifier
There are some properties that can be helpful to us if we want to restrict the type of the file to upload or set the maximum number of files that can be uploaded e.g:
<asp:AjaxFileUpload ID="AjaxFileUpload1" runat="server"
                           AllowedFileTypes="jpg,jpeg,png,gif,bmp"
                           MaximumNumberOfFiles="5"
                           onuploadcomplete="AjaxFileUpload1_UploadComplete" />
AllowedFileTypes : Using the property AllowedFileTypes, we can restrict the types of files which can be uploaded with the AjaxFileUpload control. E.g. we can prevent any file except image files (files with the extensions jpeg, png, gif or bmp) from being uploaded
MaximumNumberOfFiles : Using this property we  can limit the number of files which can be uploaded. e.g.  We can prevent a user from uploading more than 5 files.

No comments:

Post a Comment