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

Introduction: In previous articles i explained How to Upload multiple files or images through one asp.net fileupload control using jQuery plugin and  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>


Note: 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.

Asp.Net C# 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.


Asp.Net VB 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.

Now over to you:
"If you like my work; you can appreciate by leaving your comments, hitting Facebook like button, following on Google+, Twitter, Linked in and Pinterest, stumbling my posts on stumble upon and subscribing for receiving free updates directly to your inbox . Stay tuned for more technical updates. "
Previous
Next Post »

37 comments

Click here for comments
Unknown
admin
September 11, 2013 ×

its really nice one....

Reply
avatar
September 11, 2013 ×

i am glad you like my post..keep reading..

Reply
avatar
Unknown
admin
September 12, 2013 ×

thank u sir...

Reply
avatar
Anonymous
admin
September 13, 2013 ×

I am getting this error Sys.Extended is undefined

Reply
avatar
Unknown
admin
September 13, 2013 ×

Looks good, will it allow me to do drag and drop of outlook emails?

Reply
avatar
September 13, 2013 ×

Thanks Kevin.and sorry this article is for uploading multiple files..

Reply
avatar
September 13, 2013 ×

Seems there is an error in your ajaxtoolkit. Can you please paste the full error detail here so that i can help you sort out the error.

Reply
avatar
Anonymous
admin
September 17, 2013 ×

Hi I can show a server side error message using this controls? Means I have to check some files that cannot save to the server. Currently its showing successful even files are not saved on server.

Reply
avatar
September 18, 2013 ×

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 e.g.


Reply
avatar
Anonymous
admin
September 18, 2013 ×

Thank you for your suggestion. I have to validate some files not only file type, so i have to show failed message on server side. Any idea?

Reply
avatar
viney
admin
September 23, 2013 ×

i am getting error while upload files.. what to do now?

Reply
avatar
September 23, 2013 ×

Hello viney..what type of error you are getting? please paste the details here..i will help you to sort out the problem.

Reply
avatar
Daban.Sallah
admin
September 24, 2013 ×

thank you ..... but when i run it it does not give me any error but when i want to upload
it does not do anything i mean when i click on the button it doesn't open any file upload dialogbox

Reply
avatar
September 24, 2013 ×

Hello Daban Abdulla..I think you are missing something in your code..so i suggest you to recheck all of your code with this article and try once again..if still you face error then let me know..i will try to sort out your issue..

Reply
avatar
Anonymous
admin
September 25, 2013 ×

Hi, When i select multiple images it is uploading only one image
and for remaing images it is showing as pending

Reply
avatar
September 25, 2013 ×

Hello..i suggest you to recheck you code and also try to debug the code so that you can find the problem and resolve it.. if still you face error then let me know..i will try to sort out your issue..

Reply
avatar
Unknown
admin
October 04, 2013 ×

Hi sir..,
Thanks for giving this code.In this code small doubt sir,it will not show the file attachment,t will show the black space. what i will do.

Reply
avatar
Unknown
admin
October 04, 2013 ×

Hi sir..,
Thanks for giving this code.In this code small doubt sir,it will not show the file attachment,t will show the black space. what i will do.

Reply
avatar
Unknown
admin
October 04, 2013 ×

Hi sir..,
Thanks for giving this code.In this code small doubt sir,it will not show the file attachment,t will show the black space. what i will do.

Reply
avatar
October 05, 2013 ×

Hello Ankamma Rao..this article will allow you to upload multiple images at once and then that images will get displayed in the DataList control..What exactly you want?

Reply
avatar
Unknown
admin
October 09, 2013 ×

hello sir,
can you provide code for uploading multiple image after resizing and after resizing image it should be saved into root folder and in database only image name saved

Reply
avatar
October 09, 2013 ×

Hi Ajay..you can read my articles:
How to resize image in Asp.net?
http://www.webcodeexpert.com/2013/04/how-to-resize-image-in-aspnet.html

How to bind,upload,download,delete image files from the GridView in asp.net using Sql Server as a back end database
http://www.webcodeexpert.com/2013/08/how-to-binduploaddownloaddelete-image.html

After reading these articles you will be able to fulfill your requirement..I will also create an articles as per your requirement and upload that very soon..so stay connected and keep reading :)

Reply
avatar
Manvendra
admin
November 14, 2013 ×

i want to save some other value remaning image name & image path ,but i am not able to save when we use any asp control value .plz help me

Reply
avatar
December 05, 2013 ×

i want to save a another textbox value but retrive textbox value is empty in onuploadcomplete method. plz help me

Reply
avatar
Bebins
admin
December 12, 2013 ×

Hi i set MaximumNumberOfFiles="1" but it allowed to upload more files also...

Reply
avatar
Unknown
admin
January 02, 2014 ×

Brilliant article thank you, though I have a query. I can upload multiple files no problem, but any additional code (apart from the file save) that I add in AjaxFileUpload1_UploadComplete does not execute at all. If I put any code before the file save then the save itself wont work, any code after the save works but additional code doesn't work I am totally baffled. Any suggestions would be most appreciated.

Reply
avatar
Unknown
admin
February 14, 2014 ×

Hell sir,
How to upload .MDF or ms access database file for save in folder using fileupload control in asp.net c#?.

Reply
avatar
angshu44
admin
April 03, 2014 ×

your post is very useful and your way of demonstration is very helpful and easy to understand.
but i have one suggestion to you that if you modify this post with a remove button(including code) in the bottom of uploaded image where user can delete the uploaded image; that would be more suitable for user....
thank you again...

Reply
avatar
April 03, 2014 ×

Thanks angshu44 for your feedback and suggestions...i will update the article as per your suggestion. so stay connected and keep reading..:)

Reply
avatar
Anonymous
admin
April 20, 2014 ×

but how can i display image after i search it

Reply
avatar
Unknown
admin
May 07, 2014 ×

dude nice article.this very much helpful.please keep on posting your articles.helpful to us

Reply
avatar
May 08, 2014 ×

Thanks deva prasad for your feedback..it is always nice to hear that my articles helped anyone..keep reading and stay connected..

Reply
avatar
Bechir
admin
June 10, 2014 ×

Hi Lalit,
first of all, Thank you for your post.
I get the ajaxfileUpload working under Chrome and Firefox and not under IE, is there known Bug?

Reply
avatar
Unknown
admin
August 07, 2014 × This comment has been removed by the author.
avatar
October 26, 2014 ×

Thanks ashish..i am glad you found this article useful..

Reply
avatar
Unknown
admin
December 30, 2015 ×

I can't upload file in existing records(edit mode) can you give solution

Reply
avatar

If you have any question about any post, Feel free to ask.You can simply drop a comment below post or contact via Contact Us form. Your feedback and suggestions will be highly appreciated. Also try to leave comments from your account not from the anonymous account so that i can respond to you easily..