Uploading Files using AJAX Uploader with Drag and Drop Functionalities

Raj.Trivedi
Posted by in ASP.NET AJAX category on for Intermediate level | Points: 250 | Views : 17312 red flag
Rating: 5 out of 5  
 1 vote(s)

In this article we will see how we can upload multiple files using AJAX uploader with drag and drop functionality and also with a progress bar and storing the file path in database.

Introduction


Couple of days back my friend was assigned a task to upload multiple files with drag and drop functionality showing progress bar.After researching a bit came to know that Microsoft recently had released AJAX File Uploader which fits perfect for this task. 


Objective

  1. Drag and Drop Files
  2. Upload Multiple files to folder and save the path to database.
  3. Understand AJAX File Uploader
  4. Validate file Types
  5. Restrict No.of Files to be uploaded

Using the code


In order to embed AJAX Control Toolkit please use this article as resource


Follow the 1 - 12 Steps.

Remember :- We are working with AJAX File Up-loader so we need to drag and drop AJAX File Up-loader and not A SYNC Up-loader.

AJAX File Up-loader :-  

  1. AJAX File Up-loader will allow us to upload multiple files to the server asynchronously.This particular control will work best with Browsers that support HTML 5.
  2. Here are some browsers : - Internet Explorer 10, Mozilla Firefox 9,Safari 5 +
  3. The control itself has a progress bar that is shown while uploading the files.
  4. If the browser does not support HTML 5 API for E.g IE 9 or down version,then to show progress bar we can use throbber property of the control and in that we can keep an .GIF Image to show the progress bar.

Here is how the code for AJAX File Uploader Looks like

<asp:AjaxFileUpload ID="ajxFileUpload" runat="server" ThrobberID="Progressbar" AllowedFileTypes="jpg,jpeg,png,gif"
            onuploadcomplete="ajxFileUpload_UploadComplete" />
             <br />
        <br />

Explanation of Throbber Property

ThrobberID = This property will contain the ID of the Image that will show the loading progressbar while a heavy file is uploaded.

Event Name :- OnUploadedComplete
Assigned Function :- ajxFileUpload_UploadComplete
Description :- In this we actually defining the logic to upload the Images using Server.Mappath and using the SAVEAS method to save the image in the folder and then performing SQL Insert Execution.

How to validate file types ?

To validate file types we can use AllowedFileTypes property and can define the extension without (.) in "" such as

E.G:- AllowedFileTypes="jpg,jpeg,png,gif" 

Over here only the file types having the above extension.

If you want to restrict the user to upload only 5 files at a time we can use 

MaximumNumberOfFiles property and set its value

E.g. :- MaximumNumberOfFiles="5"

This will restrict the user to upload only 5 files at one time

// Tables and Stored Procedure
USE [DNF]
GO

/****** Object:  Table [dbo].[Images]    Script Date: 07/02/2013 22:29:13 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE
[dbo].[Images](
       
[ID] [int] IDENTITY(1,1) NOT NULL,
       
[Imagepath] [varchar](max) NULL
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO


USE
[DNF]
GO

/****** Object:  StoredProcedure [dbo].[GetImages]    Script Date: 07/02/2013 22:29:20 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

create proc
[dbo].[GetImages]
as
begin
select * from Images
end
GO

USE
[DNF]
GO

/****** Object:  StoredProcedure [dbo].[InsertImages]    Script Date: 07/02/2013 22:29:37 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

create proc
[dbo].[InsertImages]
(
@Imagepath varchar(max)
)
as
begin
insert
into Images(Imagepath) values(@Imagepath)
end
GO
HTML Mark UP
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DragandDropContril.aspx.cs" Inherits="DragandDropContril" %>

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        #form1
        {
            text-align: center;
        }
        .style1
        {
            font-family: "Copperplate Gothic Bold";
            font-size: x-large;
        }
    </style>
</head>

<body>
    <form id="form1" runat="server">
    <asp:toolkitscriptmanager ID="Toolkitscriptmanager1" runat="server"></asp:toolkitscriptmanager>
    <br />
    <span class="style1">Using AJAX File Uploader to Upload Multiple files with 
    Progress bar
    <br />
    with<br />
    drag and drop functionality.</span><div>
    
        <br />
        <br />
        <asp:AjaxFileUpload ID="ajxFileUpload" runat="server" ThrobberID="Progressbar" AllowedFileTypes="jpg,jpeg,png,gif"
            onuploadcomplete="ajxFileUpload_UploadComplete" />
             <br />
        <br />
        <asp:Image ID="Progressbar" ImageUrl="~/Images/04.gif" Style="display:None" runat="server" />

    </div>
    </form>
</body>
</html>
Code Behind.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;

public partial class DragandDropContril : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void ajxFileUpload_UploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
    {
        // Getting the File Name 
        string filename = e.FileName;

        // Setting the path to upload Images

        ajxFileUpload.SaveAs(Server.MapPath("Images/") + filename);

        // Storing the relative path to store into images
        string Imagepath = "~/Images/" + filename;
        // Opening the Connection for SQL Injection
        SqlConnection con = new SqlConnection("Data Source=AG-KKC;Initial Catalog=DNF;Persist Security Info=True;User ID=sa;Password=sqluser");
        con.Open();
        SqlCommand insertpathindb = new SqlCommand("InsertImages", con);
        insertpathindb.CommandType = CommandType.StoredProcedure;
        insertpathindb.Parameters.AddWithValue("@Imagepath", SqlDbType.VarChar).Value = Imagepath;
        insertpathindb.ExecuteNonQuery();
        con.Close();
    }
}

Drag and Drop Functionality





Uploading Files with Progress bar


Screen 3 :- New Record created for each Image path storage in database.




Conclusion


If you don't want to use drag and drop or if the browser does not support then you can select files for Uploading.

Note :- To select multiple files Press CTRL and select the files.

If you saving the image path in database you do not need to worry the number of files you select it will automatically create or insert that much records so you dont have to manually loop through the files and perform SQL Execution again and again Check Screen 3 for reference. 

Reference


Properties understood from :-

http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/AjaxFileUpload/AjaxFileUpload.aspx

Page copy protected against web site content infringement by Copyscape

About the Author

Raj.Trivedi
Full Name: Raj Trivedi
Member Level:
Member Status: Member,MVP
Member Since: 6/16/2012 2:04:41 AM
Country: India
Regard's Raj.Trivedi "Sharing is Caring" Please mark as answer if your Query is resolved
http://www.dotnetfunda.com/profile/raj.trivedi.aspx
Raj Trivedi i.e. me started my career as Support Professional and then moved on the Software development eventually reached at these skills Software Development | Enthusiastic Blogger | Content Writer | Technical Writer | Problem Solver | Lecturer on Technology Subjects | Runnerup Award Winner on www.dotnetfunda.com and firm believer in Sharing as a way of Caring Yet this much achieved its still a long way to go and there is biggest dream lying to be one of the best entrepreneurs of India in Technology Department. The Dream has just started and i hope it follows. Highlights are mentioned in details in my profile at http://in.linkedin.com/pub/raj-trivedi/30/61/b30/

Login to vote for this post.

Comments or Responses

Posted by: Sheonarayan on: 9/24/2013 | Points: 25
Hi Raj,

Thanks for nice article. Looks good.

Here is a request, could you resize the image in the article source while modifying the article so that it fits in the screen. Its uneasy to read the content in this way.

Thanks

Login to post response

Comment using Facebook(Author doesn't get notification)