Saturday, 25 July 2020

Multiple File Upload Using MVC jQuery AJAX Post

Step 1

Create a View with a file control to upload the file and a table to display the list of uploaded files. In this View, we have one textbox for username and a button to complete the upload process. 

  1. <h3>Upload File(s)</h3>  
  2. <style>  
  3.     .red {  
  4.         color: red;  
  5.     }  
  6. </style>  
  7. <form id="uploader">  
  8.     <div class="row">  
  9.         <div class="col-sm-6">  
  10.             User Name : <input type="text" id="txtuploader" />  
  11.             <br />            <br />  
  12.             <input id="fileInput" type="file" multiple>  
  13.             <br />            <br />  
  14.   
  15.             <table class="table" id="FilesList" style="visibility:hidden">  
  16.                 <tr>  
  17.                     <th>  
  18.                         Attachment(s)  
  19.                     </th>  
  20.                     <th>  
  21.                         Action  
  22.                     </th>  
  23.                 </tr>  
  24.             </table>  
  25.             <input type="button" id="btnupload" value="Upload" style="float:right" />  
  26.   
  27.         </div>  
  28.     </div>  
  29. </form>  

Step 2

The jQuery functions will perform the following functionalities:

  • Move uploaded files into a list on file change event.
  • chkatchtbl() helps to change the visibility of the files in the list based on the availability of the files.
  • DeleteFile() will remove selected files in the list on the click of "Remove" button
  • On click of the Upload button, it will call the controller using jQuery AJAX POST method.
  1. <script>  
  2.         var formdata = new FormData(); //FormData object  
  3.         $(document).ready(function () {  
  4.   
  5.             $("#fileInput").on("change"function () {  
  6.                 var fileInput = document.getElementById('fileInput');  
  7.                 //Iterating through each files selected in fileInput  
  8.                 for (i = 0; i < fileInput.files.length; i++) {  
  9.   
  10.                     var sfilename = fileInput.files[i].name;  
  11.                     let srandomid = Math.random().toString(36).substring(7);  
  12.   
  13.                     formdata.append(sfilename, fileInput.files[i]);  
  14.   
  15.                     var markup = "<tr id='" + srandomid + "'><td>" + sfilename + "</td><td><a href='#' onclick='DeleteFile(\"" + srandomid + "\",\"" + sfilename +  
  16.                         "\")'><span class='glyphicon glyphicon-remove red'></span></a></td></tr>"// Binding the file name  
  17.                     $("#FilesList tbody").append(markup);  
  18.   
  19.                 }  
  20.                 chkatchtbl();  
  21.                 $('#fileInput').val('');  
  22.             });  
  23.   
  24.             $("#btnupload").click(function () {  
  25.                 formdata.append('uploadername', $('#txtuploader').val());  
  26.                 $.ajax({  
  27.                     url: '/Home/UploadFiles',  
  28.                     type: "POST",  
  29.                     contentType: false// Not to set any content header  
  30.                     processData: false// Not to process data  
  31.                     data: formdata,  
  32.                     async: false,  
  33.                     success: function (result) {  
  34.                         if (result != "") {  
  35.                             alert(result);  
  36.                         }  
  37.                     },  
  38.                     error: function (err) {  
  39.                         alert(err.statusText);  
  40.                     }  
  41.                 });  
  42.             });  
  43.         });  
  44.         function DeleteFile(Fileid, FileName) {  
  45.             formdata.delete(FileName)  
  46.             $("#" + Fileid).remove();  
  47.             chkatchtbl();  
  48.         }  
  49.         function chkatchtbl() {  
  50.             if ($('#FilesList tr').length > 1) {  
  51.                 $("#FilesList").css("visibility""visible");  
  52.             } else {  
  53.                 $("#FilesList").css("visibility""hidden");  
  54.             }  
  55.         }  
  56.     </script>  

Step 3

Finally, in the Controller, it gets the all the uploaded files. When we enter the username, it stores the uploaded files into a temporary location.

  1. public ActionResult UploadFiles()  
  2. {  
  3.     string uname = Request["uploadername"];  
  4.     HttpFileCollectionBase files = Request.Files;  
  5.     for (int i = 0; i < files.Count; i++)  
  6.     {  
  7.         HttpPostedFileBase file = files[i];  
  8.         string fname;  
  9.         // Checking for Internet Explorer      
  10.         if (Request.Browser.Browser.ToUpper() == "IE" || Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER")  
  11.         {
  12.             string[] testfiles = file.FileName.Split(new char[] { '\\' });  
  13.             fname = testfiles[testfiles.Length - 1];  
  14.         }  
  15.         else  
  16.         {
  17.             fname = file.FileName;  
  18.         }  
  19.         // Get the complete folder path and store the file inside it.      
  20.         fname = Path.Combine(Server.MapPath("~/Uploads/"), fname);  
  21.         file.SaveAs(fname);  
  22.         }  
  23.         return Json("Hi, " + uname + ". Your files uploaded successfully", JsonRequestBehavior.AllowGet);
  24.     }
  25. }

No comments:

Post a Comment