ASPSnippets

Alerts
Get notified when a new article is published.

Name
 
Email

Your email will always be private and will not be shared.

Follow us on twitter.
 
Multiple File Uploads Gmail Style using JQuery and ASP.Net
Author Name: Mudassar Khan Published Date: August 19, 2009
Filed Under :
Views: 11499

This has been asked several times in ASP.Net forums about how to upload multiple files AJAX style along with progress bar similar to the Google’s GMAIL

And the answer is Uploadify plugin for JQuery which does the same in few simple steps. In this article I’ll explain the same.

 

Step 1

Download the Uploadify JQuery plugin and the JQuery Library using the links below.


Download JQuery

Download Uploadify

Once downloaded you’ll need to place the below four files

1. jquery-1.3.2.min.js

2. jquery.uploadify.js

3. uploader.fla

4. uploader.swf

in a folder called scripts in the root folder of your ASP.Net website application

 

Step 2

Start Visual Studio, create a new website and do as done below

 

Inherit the following files you downloaded earlier in the head section of the aspx or the master page

<link rel="Stylesheet" type="text/css" href="CSS/uploadify.css" />

<script type="text/javascript" src="scripts/jquery-1.3.2.min.js"></script>

<script type="text/javascript" src="scripts/jquery.uploadify.js"></script>

 

Add an ASP.Net FileUpload Control to the form tag

<form id="form1" runat="server">

    <div style = "padding:40px">

        <asp:FileUpload ID="FileUpload1" runat="server" />

    </div>

</form>

 

Place the following script in the head section or the ContentPlaceHolder in case you are using Master Pages

<script type = "text/javascript">

$(window).load(

    function() {

    $("#<%=FileUpload1.ClientID %>").fileUpload({

        'uploader': 'scripts/uploader.swf',

        'cancelImg': 'images/cancel.png',

        'buttonText': 'Browse Files',

        'script': 'Upload.ashx',

        'folder': 'uploads',

        'fileDesc': 'Image Files',

        'fileExt': '*.jpg;*.jpeg;*.gif;*.png',

        'multi': true,

        'auto': true

    });

   }

);

</script>  

 

As you can see we need to specify some settings along with the FileUpload control. The complete list of settings and their description is available here

 

Important setting to point out is 'script': 'Upload.ashx'  which will handle the FileUpload and save the uploaded files on to the disk.

Below is the code for the Upload.ashx file

    

 

C#

<%@ WebHandler Language="C#" Class="Upload" %>

 

using System;

using System.Web;

using System.IO;

 

public class Upload : IHttpHandler {

   

    public void ProcessRequest (HttpContext context) {

        context.Response.ContentType = "text/plain";

        context.Response.Expires = -1;

        try

        {

            HttpPostedFile postedFile = context.Request.Files["Filedata"];

           

            string savepath = "";

            string tempPath = "";

            tempPath = System.Configuration.ConfigurationManager.AppSettings["FolderPath"];

            savepath = context.Server.MapPath(tempPath);

            string filename = postedFile.FileName;

            if (!Directory.Exists(savepath))

                Directory.CreateDirectory(savepath);

 

            postedFile.SaveAs(savepath + @"\" + filename);

            context.Response.Write(tempPath + "/" + filename);

            context.Response.StatusCode = 200;

        }

        catch (Exception ex)

        {

            context.Response.Write("Error: " + ex.Message);

        }

    }

 

    public bool IsReusable {

        get {

            return false;

        }

    }

}

 

VB.Net

<%@ WebHandler Language="VB" Class="UploadVB" %>

 

Imports System

Imports System.Web

Imports System.IO

 

Public Class UploadVB : Implements IHttpHandler

   

    Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest

        Dim postedFile As HttpPostedFile = context.Request.Files("Filedata")

 

        Dim savepath As String = ""

        Dim tempPath As String = ""

        tempPath = System.Configuration.ConfigurationManager.AppSettings("FolderPath")

        savepath = context.Server.MapPath(tempPath)

        Dim filename As String = postedFile.FileName

        If Not Directory.Exists(savepath) Then

            Directory.CreateDirectory(savepath)

        End If

 

        postedFile.SaveAs((savepath & "\") + filename)

        context.Response.Write((tempPath & "/") + filename)

        context.Response.StatusCode = 200

    End Sub

 

    Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable

        Get

            Return False

        End Get

    End Property

 

End Class

 

As you will notice that the handler simply accepts the posted files and saves the file in folder called uploads inside the website root directory whose path is placed in an AppSettings key in the Web.Config file Refer below

<appSettings>

    <add key ="FolderPath" value ="uploads"/>

</appSettings >

 

 

That’s all you need to do now run the application and you’ll notice your website running

 

Browsing the File


Uploading Multiple Files like GMAIL in ASP.Net with AJAX and progressbar



Selecting Multiple Files Simultaneously


Selecting Multiple files in single browse ASP.Net



Uploading Multiple Files with upload progress


Uploading Multiple Files with Upload progress using AJAX ASP.Net

You might have noticed that the files are auto uploaded once browsed if you do not want this feature you can simply set the 'auto' settings to false. But in that case you’ll need to provide a trigger the uploading of files on user interaction by placing an Upload button

First you’ll need to set the Auto Upload setting to false refer the bold part

<script type = "text/javascript">

$(window).load(

    function() {

        $("#<%=FileUpload1.ClientID%>").fileUpload({

        'uploader': 'scripts/uploader.swf',

        'cancelImg': 'images/cancel.png',

        'buttonText': 'Browse Files',

        'script': 'Upload.ashx',

        'folder': 'uploads',

        'fileDesc': 'Image Files',

        'fileExt': '*.jpg;*.jpeg;*.gif;*.png',

        'multi': true,

        'auto': false

    });

   }

);

</script>

 

Then add the following link that will trigger the upload

<a href="javascript:$('#<%=FileUpload1.ClientID%>').fileUploadStart()">Start Upload</a>

 

That’s it now until user clicks the above link uploading of files won’t take place. Now since the upload is triggered by user it would be great to give him an additional link to clear the browsed files in one go

<a href="javascript:$('#<%=FileUpload1.ClientID%>').fileUploadClearQueue()">Clear</a>



The above code has been tested in the following browsers

Internet Explorer  FireFox  Chrome  Safari  Opera 

* All browser logos displayed above are property of their respective owners.


That’s it. Hope you liked the article. You can download the sample source code in VB.Net and C# using the link below

MultipleFilesUpload.zip (57.08 kb)



If you like this article, help us grow by bookmarking this page on any social bookmarking site.
Bookmark and Share Page copy protected against web site content infringement by Copyscape


Comments

Shrikant Patil said:
The Functionality is not working with IP address.Showing some errors.Please reply as soon as possible.
April 14, 2010  

Mudassar Khan said:
Reply To: Shrikant Patil
Your question is not clear. What do you meam by IP Addresses?
April 14, 2010  

Ahmed said:
it seem very good br but what if i want to save the image to more than one folder br what can i do
April 21, 2010  

Mudassar Khan said:
Reply To: Ahmed
You can save multiple times

postedFile.SaveAs("Folder1_Path");
postedFile.SaveAs("Folder2_Path");
April 21, 2010  

Pardeep said:
Hi Therebr br Thanks for your this article although it help me a lot but i have one query that i want to make the files uploaded only to maximum of 3-4. so reply me that how can set this limit..br br Thanksbr Pardeepbr
April 24, 2010  

Mudassar Khan said:
Reply To: Pardeep
What did you meant bt 3-4? 3-4 MB or 3-4 Files?
April 25, 2010  

Jineesh said:
thanks for the script. But my uploads folder doesnt contain any files. There is no error occured. The upload completed message also appears. I am working with IIS7.br br Please help me
May 13, 2010  

Mudassar Khan said:
Reply To: Jineesh
Make sure the folder path is correct because there is no reason why it will not work
May 15, 2010  

safa said:
Hithanks for your articleit works properly on my local systembut when put the files on remote progress bar will complete rapidly and no file will upload . what is the problem
May 18, 2010  

Mudassar Khan said:
Reply To: safa
Try to add some logging code to see what happens since it is difficult to predict what can be the issue
May 19, 2010  

Hieu Huynh Thanh said:
my fileUploader does not work when I submit it.br br Error message from safari browser:br Safari cant open the page http:localhost:11089MusicWebadminUpload.aspx. The error is: unknown error (kCFErrorDomainWinSock:10053) Please choose Help Report Bugs to Apple note the error number and describe what you did before you saw this message.
June 23, 2010  

Mudassar Khan said:
Reply To: Hieu Huynh Thanh
Please report the issue on Uploadify Forum as this is something related to their plugin

http://www.uploadify.com/forum/
June 24, 2010  

Hieu Huynh Thanh said:
Ok I know why it didnt work.br cause I uploaded a file with file size larger than 4MB and now I fixed it but I just can upload with FileUpload normal way no progress bar of Uploadify.br May be I have to check it out at uploadify forum.br Thanks.
June 26, 2010  

Mudassar Khan said:
Reply To: Hieu Huynh Thanh
Make sure you have installed Adobe Flash plugin for your browser
June 26, 2010  

Amanjeet singh said:
How can i save the uploaded files path to the database
July 04, 2010  

Mudassar Khan said:
Reply To: Amanjeet singh
You can always take help of the search on this site.
BTW here is the article you are looking for
http://aspsnippets.com/Articles/Save-and-Retrieve-Files-from-SQL-Server-Database-using-ASP.Net.aspx
July 06, 2010  

Add Comments

You can add your comment about this article using the form below. Make sure you provide a valid email address
else you won't be notified when the author replies to your comment

Please note that all comments are moderated and will be deleted if they are
  • Not relavant to the article
  • Spam
  • Advertising campaigns or links to other sites
  • Abusive content.
There is no need to add BR tags. Simply press enter for new line

Name*  
Email*
Comment*  
Security code
Security code