Multi File Upload through Ajax and MVC

The multiple attribute in HTML5 allows user to select multiple files from the browse window. Through ajax we can upload the selected files simultaneously. We can use XMLHttpRequest to upload the files to server asynchronously. The data transfer can be tracked with the event listeners.

By this we can know how much data is transferred to the server. This is useful when we want to show some progress bar to the user while the file is being uploaded. Here is the sample JavaScript code to send data asynchronously.

JavaScript:

  1. var requests = new Array();  
  2. var xmlRequests = new Array();  
  3. var xhr = new XMLHttpRequest();  
  4. var uploadObj = xhr.upload;  
  5. requests.push(uploadObj);  
  6. xmlRequests.push(xhr);  
  7.   
  8. uploadObj.addEventListener("progress"function(ex) {  
  9.     var pc = parseInt(((ex.loaded / ex.total) * 100)); //tells how much percentage of data is uploaded.   
  10. }  
  11.   
  12. }, false);  
  13.   
  14. xhr.open('POST'"Service Url"true);  
  15. xhr.onreadystatechange = function(response) {  
  16.     if (this.readyState != 4) return;  
  17.     if (this.status == 200) {  
  18.         // called after file has been uploaded successfully   
  19.     }  
  20. };  
  21. xhr.send(data);  
The above sample code is for single file upload. If we want to upload multiple then we need to include it in a for loop. To support multi upload the file control must contain multiple attribute as below.

HTML:
  1. <form action="action url">   
  2.    Select images: <input type="file" name="file" multiple>   
  3.    <input type="submit">   
  4. </form>   
The HttpPostedFileBase is the class which Serves as the base class for classes that provide access to individual files that have been uploaded by a client. This class we can define as a parameter in action method of the controller. The name of the file control should match with the parameter in controller. Here is a sample code. In this example I am restricting file upload size to 2 MB.
  1. public ActionResult UploadFiles(HttpPostedFileBase file) {  
  2.     string fileName = "";  
  3.     bool IsSucceeded = false;  
  4.     string Message = string.Empty;  
  5.   
  6.     string path = Server.MapPath("~/Temp");  
  7.     fileName = new FileInfo(file.FileName).Name;  
  8.     if (file.ContentLength <= (2 * 1024 * 1024)) {  
  9.         file.SaveAs(path + "/" + fileName);  
  10.         IsSucceeded = true;  
  11.     } else {  
  12.         Message = "Failed: Max limit 2MB";  
  13.     }  
  14.   
  15.   
  16.     return Json(new {  
  17.         Success = IsSucceeded, Url = fileName, Message = Message  
  18.     });  
  19. }  
Note: I have attached fully working example for multi file upload. You can download it to see demo.