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:
- 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.
View(Index.cshtml)
- <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 () {
- // Checking whether FormData is available in browser
- if (window.FormData !== undefined) {
- var fileUpload = $("#FileUpload1").get(0);
- var files = fileUpload.files;
- // Create FormData object
- var fileData = new FormData();
- // Looping over all files and add it to FormData object
- for (var i = 0; i < files.length; i++) {
- fileData.append(files[i].name, files[i]);
- }
- // Adding one more key to FormData object
- fileData.append('username', ‘Manas’);
- $.ajax({
- url: '/Home/UploadFiles',
- type: "POST",
- contentType: false, // Not to set any content header
- processData: false, // Not to process data
- 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()
- {
- // Checking no of files injected in Request object
- if (Request.Files.Count > 0)
- {
- try
- {
- // Get all files from Request object
- HttpFileCollectionBase files = Request.Files;
- for (int i = 0; i < files.Count; i++)
- {
- //string path = AppDomain.CurrentDomain.BaseDirectory + "Uploads/";
- //string filename = Path.GetFileName(Request.Files[i].FileName);
- HttpPostedFileBase file = files[i];
- string fname;
- // Checking for Internet Explorer
- 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;
- }
- // Get the complete folder path and store the file inside it.
- fname = Path.Combine(Server.MapPath("~/Uploads/"), fname);
- file.SaveAs(fname);
- }
- // Returns message that successfully uploaded
- 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.

Reza NabilooPosted Jul 26, 2022, 12:18 PM
I add this part to web.config but not working. <system.webServer> <security> <requestFiltering> <requestLimits maxAllowedContentLength="5637020" /> </requestFiltering> </security> </system.webServer>
Reza NabilooPosted Jul 26, 2022, 12:17 PM
Thank you very much for this article. but i can't upload file 5mb ???
Ravi KumarPosted Mar 10, 2021, 2:12 AM
Thank you very much for this article.
Aamir HusnainPosted Oct 12, 2020, 1:58 PM
Thank you very much this article is very helpful for me .your contribution in this domain is much apricated.
Dima AlekPosted Jul 30, 2020, 12:44 PM
And if I want to save file into my database without any folder?
Michael EzzatPosted Feb 5, 2020, 8:57 AM
Not working !!!!!
Jithin JoyPosted Jul 15, 2019, 8:21 AM
Sir i got an issue while uploading the file through ajax call.If we select the file first then edit it in a notepad and then save the file,then click the upload button.The following error will shown."<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\"\"http://www.w3.org/TR/html4/strict.dtd\"> <HTML><HEAD><TITLE>Bad Request</TITLE> <META HTTP-EQUIV=\"Content-Type\" Content=\"text/html; charset=us-ascii\"></HEAD> <BODY><h2>Bad Request</h2> <hr><p>HTTP Error 400. The request is badly formed.</p> </BODY></HTML> "
Najmul IslamPosted Apr 30, 2019, 9:48 AM
Sir I have 2 file upload such as Photograph and Signature, but I want to Upload Only Photograph , and not signature. how to handle above code...please help me sir
Syam MaddiPosted Apr 28, 2019, 3:45 AM
All, I am getting Request.Files.Count is "0" any idea where i am missing.
Sachin WankhedePosted Feb 3, 2019, 11:25 PM
How to pass variable to controller with file
Ajay GuptaPosted Oct 24, 2018, 7:49 AM
How i will get this value "fileData.append('username', ‘Manas’); " at server side?
Pancaz KumarPosted Oct 1, 2018, 1:24 PM
Thanx its worked
Farhan AhmedPosted Jul 24, 2018, 5:06 AM
Nice article...........
Moslem HadiPosted Jul 14, 2018, 11:32 PM
Whats the maximum size for file?? I tried a 70mb file, a "not found" error prompted.
Devender SharmaPosted Jun 1, 2018, 4:38 AM
Very Nice article,It helped a lot.Thanks.
Pooja PardeshiPosted May 23, 2018, 5:48 AM
I am trying the same thing but its not hitting to the function which is in controller.
Mahfuzur RahmanPosted Apr 28, 2018, 10:56 AM
Thanks, man, Really helpful
Cesar ZamoraPosted Apr 9, 2018, 10:46 AM
It is not working for me, using Visual Studio 2017. No use HttpFileCollectionBase, instead IFORMFILE. Still try to upload the files to the controller. Any ideas?
Mohamed rafeequePosted Nov 29, 2017, 5:57 AM
Wow very usefull its working fine for me.
Srikanth SrikanthPosted Nov 1, 2017, 12:01 PM
This is absolute class..
Neha AgrawalPosted Aug 28, 2017, 5:39 AM
In this how to remove a uploaded file
Neha AgrawalPosted Aug 24, 2017, 1:58 AM
How to remove a uploaded file from database
babu narayananPosted Aug 14, 2017, 6:30 AM
This a exactly what i was looking for excellent article
supreet sethiPosted Feb 27, 2017, 7:02 AM
Relay such a helpful article.
Ricky NinoPosted Jan 17, 2017, 11:29 PM
This is very helpful. Thank you.However in my case i needed to save the file with my own naming convention. How can I do that with the code provided?
Parameswaran RPosted Dec 16, 2016, 8:53 AM
Iam eagerly waiting for your reply. I got issue..
Parameswaran RPosted Dec 16, 2016, 7:09 AM
How to get Username in controller part?. Form data having two values one is Attached file and second one is your name 'Manas'. How to your name in Controller
Zafer YilmazPosted Dec 11, 2016, 10:05 AM
Thanks a lot for the share!!! nice work
Cường HoàngPosted Nov 17, 2016, 12:21 PM
Thank you very much. i need this
Manav PandyaPosted Oct 5, 2016, 10:21 AM
Nice one sir ...
Pradeep SahooPosted May 28, 2016, 11:03 PM
Nice article
Upendra Pratap ShahiPosted Apr 15, 2016, 5:36 AM
nice article...
Gowtham RajamanickamPosted Apr 9, 2016, 9:34 AM
Niceone...
Ramchandra MagarPosted Feb 5, 2016, 1:18 PM
Thanks for share...
Deepak SinghPosted Jan 27, 2016, 9:59 AM
Very good Example Thanks Borther ..It helped alot.
Raja TPosted Dec 30, 2015, 9:58 PM
Nice, thanks for sharing
sreenivasa kPosted Dec 30, 2015, 4:14 PM
nice
Ankur MistryPosted Dec 30, 2015, 9:43 AM
helpful Article
Rupesh KahanePosted Dec 30, 2015, 6:06 AM
Good one
Santhakumar MunuswamyPosted Dec 30, 2015, 4:13 AM
Thanks for nice article
Humayun Kabir MamunPosted Dec 30, 2015, 3:39 AM
Nice...
Sibeesh VenuPosted Dec 30, 2015, 3:32 AM
Nice Share