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?
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:
- FormData.append(): It appends a new value to FormData object. If key is not exists then creates a new key.
- FormData.delete(): It deletes a key-value pair from object.
- FormData.entries(): It helps to iterate over all key-value pairs present in object.
- FormData.get(): It returns value of given key within FormData object.
- FromData.has(): It returns a Boolean value whether a given key is present inside object.
- FormData.keys(): It helps to get all keys present inside object.
- FormData.set(): It helps to set/update a new value to existing keys or add new key-value pair if doesn’t exist.
- 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.
- <input type="file" id="FileUpload1" />
- <input type="button" id="btnUpload" value="Upload Files" />
-
- <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
- <script>
- $(document).ready(function(){
- $('#btnUpload').click(function () {
-
-
- if (window.FormData !== undefined) {
-
- var fileUpload = $("#FileUpload1").get(0);
- var files = fileUpload.files;
-
-
- var fileData = new FormData();
-
-
- for (var i = 0; i < files.length; i++) {
- fileData.append(files[i].name, files[i]);
- }
-
-
- fileData.append('username', ‘Manas’);
-
- $.ajax({
- url: '/Home/UploadFiles',
- type: "POST",
- contentType: false,
- processData: false,
- data: fileData,
- success: function (result) {
- alert(result);
- },
- error: function (err) {
- alert(err.statusText);
- }
- });
- } else {
- alert("FormData is not supported.");
- }
- });
- });
- </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:
- [HttpPost]
- public ActionResult UploadFiles()
- {
-
- if (Request.Files.Count > 0)
- {
- try
- {
-
- HttpFileCollectionBase files = Request.Files;
- for (int i = 0; i < files.Count; i++)
- {
-
-
-
- HttpPostedFileBase file = files[i];
- string fname;
-
-
- if (Request.Browser.Browser.ToUpper() == "IE" || Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER")
- {
- string[] testfiles = file.FileName.Split(new char[] { '\\' });
- fname = testfiles[testfiles.Length - 1];
- }
- else
- {
- fname = file.FileName;
- }
-
-
- fname = Path.Combine(Server.MapPath("~/Uploads/"), fname);
- file.SaveAs(fname);
- }
-
- return Json("File Uploaded Successfully!");
- }
- catch (Exception ex)
- {
- return Json("Error occurred. Error details: " + ex.Message);
- }
- }
- else
- {
- return Json("No files selected.");
- }
- }
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:
- <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 here. The 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.