Upload Multiple Files Using jQuery AJAX and JQueryUI Progressbar With ASP.Net Generic Handler

Objective

Our main objective is to upload multiple files at once and save them in a local folder. Also, we want to show a progress bar until the uploading is complete with a message to prompt the user that the files have been uploaded successfully.

Method

To do it, we will use an ASP.NET generic HTTP handler to get the files and save them to the local folder. Using jQuery Ajax we will pass the files to the handler using the post request. Also, to show the processing, we will be using jQueryUI Progressbar. Now, let’s see how to do this.

Step 1

Create an empty ASP.NET web application in Visual Studio IDE.

web application

Step 2

Go to jqueryui.com and select the download tab. Then, click the Progressbar checkbox and click the download button at the bottom of the page.

download builder

widgets

download

Step 3

A Zip file will be downloaded. Unzip this file and copy the complete folder to your project.

jQuery package

Step 4

Add a Generic Handler to the project and name it UploadHandler.

UploadHandler

Step 5

Add a folder to the project and name it UploadedFiles.

UploadedFiles

Step 6

Write the following code in UploadHandler.cs.

  1. using

     System.Web;  

  2. namespace

     MulFileUpJqueryASPHandler  

  3. {  

  4.     

    public

     

    class

     UploadsHandler : IHttpHandler  

  5.     {  

  6.         

    public

     

    void

     ProcessRequest(HttpContext context)  

  7.         {  

  8.             

    if

     (context.Request.Files.Count > 0)  

  9.             {  

  10.                 HttpFileCollection UploadedFilesCollection = context.Request.Files;  

  11.                 

    for

     (

    int

     i = 0; i < UploadedFilesCollection.Count; i++)  

  12.                 {  

  13.                     System.Threading.Thread.Sleep(2000);  

  14.                     HttpPostedFile PostedFiles = UploadedFilesCollection[i];  

  15.                     

    string

     FilePath = context.Server.MapPath(

    “~/UploadedFiles/”

     + System.IO.Path.GetFileName(PostedFiles.FileName));  

  16.                     PostedFiles.SaveAs(FilePath);  

  17.                 }  

  18.             }  

  19.         }  

  20.         

    public

     

    bool

     IsReusable  

  21.         {  

  22.             

    get

      

  23.             {  

  24.                 

    return

     

    false

    ;  

  25.             }  

  26.         }  

  27.     }  

  28. }  

Step 7

Add a Webform to the project and name it Demo.aspx.

add webform

Step 8

Add the references of the following selected files in the HTML of the Demo.aspx.

Add the references

Step 9

Add the following code to the HTML.

  1. <%@ Page Language=

    “C#”

     AutoEventWireup=

    “true”

     CodeBehind=

    “Demo.aspx.cs”

     Inherits=

    “MulFileUpJqueryASPHandler.Demo”

     %>  

  2.   

  3. <!DOCTYPE html>  

  4.   

  5. <html xmlns=

    “http://www.w3.org/1999/xhtml”

    >  

  6. <head runat=

    “server”

    >  

  7.     <title>jQuery Multiple File Upload</title>  

  8.     <script src=

    “jQuery%20Package/jquery-2.1.4.js”

    ></script>  

  9.     <link href=

    “jQuery%20Package/jquery-ui.css”

     rel=

    “stylesheet”

     />  

  10.     <script src=

    “jQuery%20Package/jquery-ui.js”

    ></script>  

  11.     <link href=

    “jQuery%20Package/jquery-ui.structure.css”

     rel=

    “stylesheet”

     />  

  12.     <link href=

    “jQuery%20Package/jquery-ui.theme.css”

     rel=

    “stylesheet”

     />  

  13.     <script type=

    “text/javascript”

    >  

  14.         $(document).ready(function () {  

  15.             $(

    ‘#btnUpload’

    ).click(function (

    event

    ) {  

  16.                 var uploadedFiles = $(

    ‘#uploader’

    )[0].files;  

  17.                 

    if

     (uploadedFiles.length > 0) {  

  18.                     var formData = 

    new

     FormData();  

  19.                     

    for

     (var i = 0; i < uploadedFiles.length; i++) {  

  20.                         formData.append(uploadedFiles[i].name, uploadedFiles[i]);  

  21.                     }  

  22.                 }  

  23.                 var progressbarLabel = $(

    ‘#progressbar-label’

    );  

  24.                 var progressbarDiv = $(

    ‘#progress-bar’

    );  

  25.                 $.ajax  

  26.                     ({  

  27.                         url: 

    ‘UploadsHandler.ashx’

    ,  

  28.                         method: 

    ‘post’

    ,  

  29.                         contentType: 

    false

    ,  

  30.                         processData: 

    false

    ,  

  31.                         data: formData,  

  32.                         success: function () {  

  33.                             progressbarLabel.text(

    ‘Uploaded Successfully’

    );  

  34.                             progressbarDiv.fadeOut(2000);  

  35.                         },  

  36.                         error: function (err) {  

  37.                             alert(err.statusText);  

  38.                         }  

  39.                     });  

  40.                 progressbarLabel.text(

    ‘Please Wait…’

    );  

  41.                 progressbarDiv.progressbar({  

  42.                     value: 

    false

      

  43.                 }).fadeIn(1000);  

  44.             });  

  45.         });  

  46.     </script>  

  47. </head>  

  48. <body>  

  49.     <form id=

    “form1”

     runat=

    “server”

    >  

  50.         <div>  

  51.             Select the files to be uploaded:  

  52.             <asp:FileUpload ID=

    “uploader”

     runat=

    “server”

     AllowMultiple=

    “true”

     />  

  53.             <br />  

  54.             <br />  

  55.             <input type=

    “button”

     id=

    “btnUpload”

     value=

    “Upload Now”

     />  

  56.         </div>  

  57.         <div style=

    “width:500px”

    >  

  58.             <div id=

    “progress-bar”

     style=

    “position: relative; display: none”

    >  

  59.                 <span id=

    “progressbar-label”

     style=

    “position: absolute; left: 30%; top: 20%;”

    >Please Wait…</span>  

  60.             </div>  

  61.         </div>  

  62.     </form>  

  63. </body>  

  64. </html>  

Step 10

Press F5 to run the project and you will see the following screenshots like an interface.

file uoload

output

Explanation

UploadHandler.cs

  • First we are checking, that if the user has uploaded at least one file.
  • We are saving the uploaded files in the HttpFileCollection Class’s object.
  • Using a for loop, we are iterating through each file uploaded by the user.
  • Saving each file in the HttpPostedFile Object using the index values of each uploaded file.
  • We are saving the filename with its path using the Server.MapPath method of and FileName Property in a string variable.
  • Finally we saved the file in the HttpPostedFile Object using the SaveAs method.

Add a Webform to the project and name itAdd the references of the following selected files in the HTML of theAdd the following code to the HTML.Press F5 to run the project and you will see the following screenshots like an interface.

Demo.aspx

  • Add a file upload and a button control from toolbox.
  • To display the progressbar we have created a div with 500px width.
  • We have added an inline CSS making the position relative and display is none, because, we don’t want to show the bar when the page first loads.
  • A span is added to show the text, Please Wait and its position is taken as absolute and it is relative to the parent div.

jQuery Code

  • On the click event of the button control, the files uploaded in the uploader are saved in a local variable.
  • Then we appended the formData by iterating through each file uploaded.
  • Now, using the Ajax options, we will send the data to the handler.
  • The URL is the Handler, the requestType is Post and the data is coming from formData. When it succeeds, we changed the span text to uploaded successfully and fade out in 2 seconds.
  • If an error exists, it is shown in a JavaScript alert.
  • And when the page again loads, we changed the text to Please Wait and Fade in property to 1 seconds. Also its value is false, to tell the progressbar that we will pass the data using our own customizations.

Xổ số miền Bắc