Skip to main content

Upload multiple files once selecting using JQuery in Asp.Net

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) ImplementsIHttpHandler.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>

Popular posts from this blog

Creating package in Oracle Database using Toad For Oracle

What are Packages in Oracle Database A package is  a group   of procedures, functions,  variables   and  SQL statements   created as a single unit. It is used to store together related objects. A package has two parts, Package  Specification  and Package Body.

Resolving 'Setup Account Privileges' error while installing SQL Server

A new installation of Microsoft SQL Server 2012 or Microsoft SQL Server 2008 R2 fails You see the following error message when you try to install a new instance of SQL Server 2012 or SQL Server 2008 R2: Rule "Setup account privileges" failed.

Creating Oracle stored Procedures using TOAD for Oracle

In a database management system, a  stored procedure  is a set of Structured Query Language (SQL) statements with an assigned name that's stored in the database in compiled form so that it can be shared by a number of programs. The use of  stored procedures  can be helpful in controlling  access to data, preserving  data integrity  and  improving  productivity.