Multiple File Upload using JQuery

Introduction:
Here I will explained how to build a Gmail style file uploader using JQuery and Uploadify plugin for JQuery in ASP.Net
Description:
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.

   1: <link rel="Stylesheet" type="text/css" href="CSS/uploadify.css" />
   2: <script type="text/javascript" src="scripts/jquery-1.3.2.min.js"></script>
   3: <script type="text/javascript" src="scripts/jquery.uploadify.js"></script>

Add an ASP.Net FileUpload Control to the form tag
   1: <form id="form1" runat="server">
   2:     <div style = "padding:40px">
   3:         <asp:FileUpload ID="FileUpload1" runat="server" />
   4:     </div>
   5: </form>
Place the following script in the head section or the ContentPlaceHolder in case you are using Master Pages
   1: <script type = "text/javascript">
   2: $(window).load(
   3:     function() {
   4:     $("#<%=FileUpload1.ClientID %>").fileUpload({
   5:         'uploader': 'scripts/uploader.swf',
   6:         'cancelImg': 'images/cancel.png',
   7:         'buttonText': 'Browse Files',
   8:         'script': 'Upload.ashx',
   9:         'folder': 'uploads',
  10:         'fileDesc': 'Image Files',
  11:         'fileExt': '*.jpg;*.jpeg;*.gif;*.png',
  12:         'multi': true,
  13:         'auto': true
  14:     });
  15:    }
  16: );
  17: </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#
   1: <%@ WebHandler Language="C#" Class="Upload" %>
   2:  
   3: using System;
   4: using System.Web;
   5: using System.IO;
   6:  
   7: public class Upload : IHttpHandler {
   8:    
   9:     public void ProcessRequest (HttpContext context) {
  10:         context.Response.ContentType = "text/plain";
  11:         context.Response.Expires = -1;
  12:         try
  13:         {
  14:             HttpPostedFile postedFile = context.Request.Files["Filedata"];
  15:            
  16:             string savepath = "";
  17:             string tempPath = "";
  18:             tempPath = System.Configuration.ConfigurationManager.AppSettings["FolderPath"];
  19:             savepath = context.Server.MapPath(tempPath);
  20:             string filename = postedFile.FileName;
  21:             if (!Directory.Exists(savepath))
  22:                 Directory.CreateDirectory(savepath);
  23:  
  24:             postedFile.SaveAs(savepath + @"\" + filename);
  25:             context.Response.Write(tempPath + "/" + filename);
  26:             context.Response.StatusCode = 200;
  27:         }
  28:         catch (Exception ex)
  29:         {
  30:             context.Response.Write("Error: " + ex.Message);
  31:         }
  32:     }
  33:  
  34:     public bool IsReusable {
  35:         get {
  36:             return false;
  37:         }
  38:     }
  39: }
VB.Net
   1: <%@ WebHandler Language="VB" Class="UploadVB" %>
   2:  
   3: Imports System
   4: Imports System.Web
   5: Imports System.IO
   6:  
   7: Public Class UploadVB : Implements IHttpHandler
   8:    
   9:     Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
  10:         Dim postedFile As HttpPostedFile = context.Request.Files("Filedata")
  11:  
  12:         Dim savepath As String = ""
  13:         Dim tempPath As String = ""
  14:         tempPath = System.Configuration.ConfigurationManager.AppSettings("FolderPath")
  15:         savepath = context.Server.MapPath(tempPath)
  16:         Dim filename As String = postedFile.FileName
  17:         If Not Directory.Exists(savepath) Then
  18:             Directory.CreateDirectory(savepath)
  19:         End If
  20:  
  21:         postedFile.SaveAs((savepath & "\") + filename)
  22:         context.Response.Write((tempPath & "/") + filename)
  23:         context.Response.StatusCode = 200
  24:     End Sub
  25:  
  26:     Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
  27:         Get
  28:             Return False
  29:         End Get
  30:     End Property
  31:  
  32: 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
   1: <appSettings>
   2:     <add key ="FolderPath" value ="uploads"/>
   3: </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
   1:  
   2: <script type = "text/javascript">
   3: $(window).load(
   4: function() {
   5: $("#<%=FileUpload1.ClientID%>").fileUpload({
   6: 'uploader': 'scripts/uploader.swf',
   7: 'cancelImg': 'images/cancel.png',
   8: 'buttonText': 'Browse Files',
   9: 'script': 'Upload.ashx',
  10: 'folder': 'uploads',
  11: 'fileDesc': 'Image Files',
  12: 'fileExt': '*.jpg;*.jpeg;*.gif;*.png',
  13: 'multi': true,
  14: 'auto': false
  15: });
  16: }
  17: );
  18: </script>
Then add the following link that will trigger the upload
   1: <a 
   2: href="javascript:$('#<%=FileUpload1.ClientID%>').fileUploadStart()">Start 
   3: 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
   1:  
   2: <a 
   3: href="javascript:$('#<%=FileUpload1.ClientID%>').fileUploadClearQueue()">Clear</a>


Technorati Tags: ,,

No comments:

Post a Comment