File Upload Through JQuery AJAX In ASP.NET MVC

Introduction
 
In this article we will discuss about how to upload files through jQuery AJAX in ASP.NET MVC.
 
Using Code
 
Start implementation, I want to introduce FormData object which is available in browser. Because with the help of FormData, we will send files to server.
 
What is FormData?
 
As stated
 
The FormData interface provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the XMLHttpRequest.send() method. It uses the same format a form would use if the encoding type were set to "multipart/form-data".
 
We can create FormData objects like var tempObject = new FormData();
 
It contains the following methods:
  1. FormData.append(): It appends a new value to FormData object. If key is not exists then creates a new key.
  2. FormData.delete(): It deletes a key-value pair from object.
  3. FormData.entries(): It helps to iterate over all key-value pairs present in object.
  4. FormData.get(): It returns value of given key within FormData object.
  5. FromData.has(): It returns a Boolean value whether a given key is present inside object.
  6. FormData.keys(): It helps to get all keys present inside object.
  7. FormData.set(): It helps to set/update a new value to existing keys or add new key-value pair if doesn’t exist.
  8. FormData.values(): Returns an iterator allowing to go through all values of the key/value pairs contained in this object. 
In this way FormData helps to send files, value to server through AJAX request. However, one disadvantage is old browsers doesn’t support FormData object and its methods.
 
Next we will design a view(index.cshtml) page where we will add the following HTML upload control and JavaScript code.
 
View(Index.cshtml)
  1. <input type="file" id="FileUpload1" />  
  2. <input type="button" id="btnUpload" value="Upload Files" />  
  3.   
  4. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>  
  5. <script>  
  6. $(document).ready(function(){  
  7.     $('#btnUpload').click(function () {  
  8.   
  9.         // Checking whether FormData is available in browser  
  10.         if (window.FormData !== undefined) {  
  11.   
  12.             var fileUpload = $("#FileUpload1").get(0);  
  13.             var files = fileUpload.files;  
  14.               
  15.             // Create FormData object  
  16.             var fileData = new FormData();  
  17.   
  18.             // Looping over all files and add it to FormData object  
  19.             for (var i = 0; i < files.length; i++) {  
  20.                 fileData.append(files[i].name, files[i]);  
  21.             }  
  22.               
  23.             // Adding one more key to FormData object  
  24.             fileData.append('username', ‘Manas’);  
  25.   
  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: fileData,  
  32.                 success: function (result) {  
  33.                     alert(result);  
  34.                 },  
  35.                 error: function (err) {  
  36.                     alert(err.statusText);  
  37.                 }  
  38.             });  
  39.         } else {  
  40.             alert("FormData is not supported.");  
  41.         }  
  42.     });  
  43. });  
  44. </script>  
In preceding code, first it checks whether windows.FormData is valid in browse. Because, using FormData we will send data to server through AJAX request. Once FormData object presence checked, it creates a new object. Then it fetches files injected in upload control and loop over it to add files to FormData object.
 
Controller (HomeController.cs)
 
In HomeContoller we need to add the following action (UploadFiles) to save files from coming AJAX request. Here is the code:
  1. [HttpPost]  
  2. public ActionResult UploadFiles()  
  3. {  
  4. // Checking no of files injected in Request object  
  5.     if (Request.Files.Count > 0)  
  6.     {  
  7.         try  
  8.         {  
  9.             //  Get all files from Request object  
  10.             HttpFileCollectionBase files = Request.Files;  
  11.             for (int i = 0; i < files.Count; i++)  
  12.             {  
  13.                 //string path = AppDomain.CurrentDomain.BaseDirectory + "Uploads/";  
  14.                 //string filename = Path.GetFileName(Request.Files[i].FileName);  
  15.   
  16.                 HttpPostedFileBase file = files[i];  
  17.                 string fname;  
  18.   
  19.                 // Checking for Internet Explorer  
  20.                 if (Request.Browser.Browser.ToUpper() == "IE" || Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER")  
  21.                 {  
  22.                     string[] testfiles = file.FileName.Split(new char[] { '\\' });  
  23.                     fname = testfiles[testfiles.Length - 1];  
  24.                 }  
  25.                 else  
  26.                 {  
  27.                     fname = file.FileName;  
  28.                 }  
  29.   
  30.                 // Get the complete folder path and store the file inside it.  
  31.                 fname = Path.Combine(Server.MapPath("~/Uploads/"), fname);  
  32.                 file.SaveAs(fname);  
  33.             }  
  34.             // Returns message that successfully uploaded  
  35.             return Json("File Uploaded Successfully!");  
  36.         }  
  37.         catch (Exception ex)  
  38.         {  
  39.             return Json("Error occurred. Error details: " + ex.Message);  
  40.         }  
  41.     }  
  42.     else  
  43.     {  
  44.         return Json("No files selected.");  
  45.     }  
  46. }  
In preceding code, first it checks no. of files appended in Request object. Next, HttpFileCollectionBase class collects all files from request object. Once it collects all files, it loop over all files and save it one by one. After saving files it returns JSON data to browser that it is successfully uploaded, and if exception occurs then it send exception message in JSON format.
 
Above code is suitable for only one file at a time but if you want to upload multiple files then you need to go for a small change. That is: add an attribute called multiple in file upload control like the following: 
  1. <input type="file" id="FileUpload1" multiple />  
Except multiple tag everything will be same in View and Controller page. You can also upload files through HTML form tag(without using AJAX), visit hereThe form(HTML) tag makes round trip to server but AJAX do not. On the other hand, if your file is larger then AJAX might throw TimeOut issue. You can overcome the issue with time out property of AJAX.
 
Reference
 
Form Data
 
Conclusion
 
In this article we discussed how to upload files to server jQuery AJAX request. You can upload files in two ways: AJAX and without AJAX (through Form tag). Choose appropriate one as per your file size and environment.
 


Similar Articles