File Upload With JQuery Progress Bar In ASP MVC

In this article we are going to learn how to implement jquery progress bar in File Upload control in ASP MVC.
 
Step 1
 
First we have to create an Asp Mvc project in visual studio. To do that, Open Visual Studio -> New Project -> A new dialog window will appear -> In left pane select C# ->select Web -> Select "ASP.NET MVC 4 Application" name your project and click ok.
 
Again a new dialog window will appear. In that select "Internet Application"
 
Please refer to the below image for your reference.
 
 
 
 
Step 2
 
Now you can see your project files in right corner of visual studio. Please refer to the below image for your reference
 
 
 
Step 3
 
Open controller folder. In that we have "Home" and "Account" controller default. It was created while creating a new project in asp mvc.
 
If you open "Home" controller , you can see some default code in that. Please refer to the below image for your reference.

 
 
Step 4
 
In view folder we can see the "Home" folder and can see the "Index" view. It was also created when we created a project.
 
If you want to create a view for your action result , just right click on your action result and click "Add View"
 
Please refer to the below image for your reference.
 
 
 
Step 5
 
Now let's change the index view code as per our requirement.
 
Please just copy and paste the code in your index view.
 
Note

Here I have added the "ProgressBar" css and script file from CDN(Content Delivery Network)
  1. @{    
  2.     ViewBag.Title = "Home Page";    
  3. }    
  4. <link href="https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"    
  5.     rel="stylesheet">   @*I got this link from Tutorials point*@    
  6. <link href="../../Content/bootstrap.css" rel="stylesheet" type="text/css" /> @*Download Bootstrap from Nuget Package manager*@    
  7. <link href="../../Content/bootstrap-theme.css" rel="stylesheet" type="text/css" />    
  8. <style>    
  9.     .ui-widget-header    
  10.     {    
  11.         background: #cedc98;    
  12.         border: 1px solid #DDDDDD;    
  13.         color: #333333;    
  14.         font-weight: bold;    
  15.     }    
  16.     .progress-label    
  17.     {    
  18.         position: absolute;    
  19.         left: 50%;    
  20.         top: 13px;    
  21.         font-weight: bold;    
  22.         text-shadow: 1px 1px 0 #fff;    
  23.     }    
  24.     .red    
  25.     {    
  26.         color: red;    
  27.     }    
  28. </style>    
  29. <div class="container">    
  30.     <h1>    
  31.         File Upload Demo</h1>    
  32.     <div id="FileBrowse">    
  33.         <div class="row">    
  34.             <div class="col-sm-4">    
  35.                 <input type="file" id="Files" />    
  36.             </div>    
  37.             <div class="col-sm-2">    
  38.                 <input type="button" id="UploadBtn" class="btn btn-danger" value="Upload" />    
  39.             </div>    
  40.         </div>    
  41.     </div>    
  42.     <div class="row">    
  43.         <div class="col-sm-4">    
  44.             <div id="progressbar-5">    
  45.                 <div class="progress-label">    
  46.                 </div>    
  47.             </div>    
  48.         </div>    
  49.     </div>    
  50.     <br />    
  51.     <div class="row">    
  52.         <div class="col-sm-6">    
  53.             <table class="table" id="ListofFiles">    
  54.                 <tr>    
  55.                     <th>    
  56.                         Files    
  57.                     </th>    
  58.                     <th>    
  59.                         Action    
  60.                     </th>    
  61.                 </tr>    
  62.             </table>    
  63.         </div>    
  64.     </div>    
  65.     <br />    
  66.     <br />    
  67.     <br />    
  68.     <br />    
  69. </div>    
  70. @section scripts{    
  71.     <script src="https://code.jquery.com/jquery-1.10.2.js"></script>      
  72.     <script src="https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>    
  73.     <script>    
  74.             
  75.         $('#UploadBtn').click(function () {    
  76.     
  77.             var fileUpload = $("#Files").get(0);    
  78.             var files = fileUpload.files;    
  79.             // Create FormData object      
  80.             var fileData = new FormData();    
  81.             // Looping over all files and add it to FormData object      
  82.             for (var i = 0; i < files.length; i++) {    
  83.                 fileData.append(files[i].name, files[i]);    
  84.             }    
  85.             $.ajax({    
  86.                 url: '/Home/UploadFiles',    
  87.                 type: "POST",    
  88.                 contentType: false// Not to set any content header      
  89.                 processData: false// Not to process data      
  90.                 data: fileData,    
  91.                 async: false,    
  92.                 success: function (result) {    
  93.                     if (result != "") {    
  94.                         $('#FileBrowse').find("*").prop("disabled"true);    
  95.                         LoadProgressBar(result); //calling LoadProgressBar function to load the progress bar.    
  96.                     }    
  97.                 },    
  98.                 error: function (err) {    
  99.                     alert(err.statusText);    
  100.                 }    
  101.             });    
  102.     
  103.         });    
  104.     
  105.         function LoadProgressBar(result) {    
  106.             var progressbar = $("#progressbar-5");    
  107.             var progressLabel = $(".progress-label");    
  108.             progressbar.show();    
  109.             $("#progressbar-5").progressbar({    
  110.                 //value: false,    
  111.                 change: function () {    
  112.                     progressLabel.text(    
  113.                      progressbar.progressbar("value") + "%");  // Showing the progress increment value in progress bar    
  114.                 },    
  115.                 complete: function () {    
  116.                     progressLabel.text("Loading Completed!");     
  117.                     progressbar.progressbar("value", 0);  //Reinitialize the progress bar value 0    
  118.                     progressLabel.text("");     
  119.                     progressbar.hide(); //Hiding the progress bar    
  120.                     var markup = "<tr><td>" + result + "</td><td><a href='#' onclick='DeleteFile(\"" + result + "\")'><span class='glyphicon glyphicon-remove red'></span></a></td></tr>"// Binding the file name    
  121.                     $("#ListofFiles tbody").append(markup);    
  122.                     $('#Files').val('');    
  123.                     $('#FileBrowse').find("*").prop("disabled"false);    
  124.                 }    
  125.             });    
  126.             function progress() {    
  127.                 var val = progressbar.progressbar("value") || 0;    
  128.                 progressbar.progressbar("value", val + 1);    
  129.                 if (val < 99) {    
  130.                     setTimeout(progress, 25);    
  131.                 }    
  132.             }    
  133.             setTimeout(progress, 100);    
  134.         }    
  135.     
  136.         function DeleteFile(FileName) {     
  137.             
  138.         //Write your delete logic here    
  139.         }    
  140.        
  141.     </script>    
  142. } 
Let;s understand the code now, I have used one file input control, html input button. Find the code here
  1. <div id="FileBrowse">    
  2.        <div class="row">    
  3.            <div class="col-sm-4">    
  4.                <input type="file" id="Files" />    
  5.            </div>    
  6.            <div class="col-sm-2">    
  7.                <input type="button" id="UploadBtn" class="btn btn-danger" value="Upload" />    
  8.            </div>    
  9.        </div>    
  10.    </div>    
  11.    <div class="row">    
  12.        <div class="col-sm-4">    
  13.            <div id="progressbar-5">    
  14.                <div class="progress-label">    
  15.                </div>    
  16.            </div>    
  17.    </div>    
  18. </div>    
I have used one html table to show the files list.find the code here.
  1. <div class="row">    
  2.         <div class="col-sm-6">    
  3.             <table class="table" id="ListofFiles">    
  4.                 <tr>    
  5.                     <th>    
  6.                         Files    
  7.                     </th>    
  8.                     <th>    
  9.                         Action    
  10.                     </th>    
  11.                 </tr>    
  12.             </table>    
  13.         </div>    
  14. </div> 
In jquery I have written upload button click event and passed the file to controller using ajax method.
 
Please find the code below,
  1. $('#UploadBtn').click(function () {   
  2.     var fileUpload = $("#Files").get(0);    
  3.     var files = fileUpload.files;    
  4.     // Create FormData object      
  5.     var fileData = new FormData();    
  6.     // Looping over all files and add it to FormData object      
  7.     for (var i = 0; i < files.length; i++) {    
  8.         fileData.append(files[i].name, files[i]);    
  9.     }    
  10.     $.ajax({    
  11.         url: '/Home/UploadFiles',    
  12.         type: "POST",    
  13.         contentType: false// Not to set any content header      
  14.         processData: false// Not to process data      
  15.         data: fileData,    
  16.         async: false,    
  17.         success: function (result) {    
  18.             if (result != "") {    
  19.                 $('#FileBrowse').find("*").prop("disabled"true);    
  20.                 LoadProgressBar(result); //calling LoadProgressBar function to load the progress bar.    
  21.             }    
  22.         },    
  23.         error: function (err) {    
  24.             alert(err.statusText);    
  25.         }    
  26.     });  
  27. }); 
Let's create the "UploadFiles" action result in "Home" controller to receive the file from request and save the file in our "Uploads" folder.
 
Please find the code below for your reference.
  1. public ActionResult UploadFiles()  
  2. {  
  3.     string FileName="";  
  4.     HttpFileCollectionBase files = Request.Files;  
  5.     for (int i = 0; i < files.Count; i++)  
  6.     {  
  7.         //string path = AppDomain.CurrentDomain.BaseDirectory + "Uploads/";    
  8.         //string filename = Path.GetFileName(Request.Files[i].FileName);    
  9.   
  10.         HttpPostedFileBase file = files[i];  
  11.         string fname;  
  12.   
  13.         // Checking for Internet Explorer    
  14.         if (Request.Browser.Browser.ToUpper() == "IE" || Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER")  
  15.         {  
  16.             string[] testfiles = file.FileName.Split(new char[] { '\\' });  
  17.             fname = testfiles[testfiles.Length - 1];  
  18.         }  
  19.         else  
  20.         {  
  21.             fname = file.FileName;  
  22.             FileName = file.FileName;  
  23.         }  
  24.   
  25.         // Get the complete folder path and store the file inside it.    
  26.         fname = Path.Combine(Server.MapPath("~/Uploads/"), fname);  
  27.         file.SaveAs(fname);  
  28.     }  
  29.     return Json(FileName, JsonRequestBehavior.AllowGet);  
  30. }  
In Button Click event we are calling the function "LoadProgressbar" to load the progress bar and bind the fields in  the table.
 
All the code wrote in "LoadProgressBar", please find the code for your reference.
  1. function LoadProgressBar(result) {  
  2.     var progressbar = $("#progressbar-5");  
  3.     var progressLabel = $(".progress-label");  
  4.     progressbar.show();  
  5.     $("#progressbar-5").progressbar({  
  6.         //value: false,  
  7.         change: function () {  
  8.             progressLabel.text(  
  9.             progressbar.progressbar("value") + "%");  // Showing the progress increment value in progress bar  
  10.         },  
  11.         complete: function () {  
  12.             progressLabel.text("Loading Completed!");   
  13.             progressbar.progressbar("value", 0);  //Reinitialize the progress bar value 0  
  14.             progressLabel.text("");   
  15.             progressbar.hide(); //Hiding the progress bar  
  16.             var markup = "<tr><td>" + result + "</td><td><a href='#' onclick='DeleteFile(\"" + result + "\")'><span class='glyphicon glyphicon-remove red'></span></a></td></tr>"// Binding the file name  
  17.             $("#ListofFiles tbody").append(markup);  
  18.             $('#Files').val('');  
  19.             $('#FileBrowse').find("*").prop("disabled"false);  
  20.         }  
  21.     });  
  22.     function progress() {  
  23.         var val = progressbar.progressbar("value") || 0;  
  24.         progressbar.progressbar("value", val + 1);  
  25.         if (val < 99) {  
  26.             setTimeout(progress, 25);  
  27.         }  
  28.      }  
  29.      setTimeout(progress, 100);  
  30. }  
Now let's run our project. Please find the below result for your reference.
 
 
 
 
Thanks for reading my article. If you have any comments or queries, please mention in the comment box. 


Similar Articles