File Upload in Mvc Using Jquery Ajax
At that place are many ways to upload files on server, but in this I volition requite you example to upload file using jQuery Ajax, if you desire to use whatsoever eternal plugin like Dropzone.js you can read "File uploading using DropZone js & HTML5 in MVC" or if you want to Upload file using HTML.BeginForm, you tin read my commodity "Uploading Files in ASP.NET MVC C# (Single & Multiple Files)"
Earlier we proceed further I will like to that about the fashion we will upload the files using jQuery Ajax, then basically we volition be using FormData object.
About FormData
The FormData
interface provides a way to easily construct a prepare of cardinal/value pairs representing class fields and their values, which can then be easily sent using the XMLHttpRequest.send()
method.It uses the aforementioned format a form would apply if the encoding type were set to "multipart/class-information"
.
FormData methods:
- FormData.append(): Appends a new value onto an existing key inside a
FormData
object, or adds the primal if information technology does not already exist. - FormData.delete():Deletes a cardinal/value pair from a
FormData
object. - FormData.entries(): Returns an
iterator
assuasive to go through all key/value pairs contained in this object. - FormData.get(): It returns value of given key within FormData object.
- FromData.has(): It returns a Boolean value whether a given key is nowadays within object.
- FormData.keys(): Information technology helps to get all keys present inside object.
- FormData.set(): Information technology helps to gear up/update a new value to existing keys or add new primal-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.
You lot can read more about information technology from this reference
Compatibility and detection
You can verify if the client browser support the FormData or not using the below code
function supportAjaxUploadWithProgress() { return supportFileAPI() && supportAjaxUploadProgressEvents() && supportFormData(); function supportFileAPI() { var fi = document.createElement('INPUT'); fi.type = 'file'; return 'files' in fi; }; function supportAjaxUploadProgressEvents() { var xhr = new XMLHttpRequest(); return !! (xhr && ('upload' in xhr) && ('onprogress' in xhr.upload)); }; part supportFormData() { return !! window.FormData; } }
Elementary way to submit the complete HTML form using FormData
FormData
gives united states two means to interface with it. The first and simplest is: get a reference to the class
element and pass it to the FormData
constructor, similar then:
var grade = document.getElementById('grade-id'); var formData = new FormData(grade);
Another way is to call
var xhr = new XMLHttpRequest(); // any event handlers here... xhr.open('Mail service', '/upload/path', true); xhr.send(formData);
Uploading Files in MVC using jQuery AJAX FormData
I assume, you have already created the basic construction of MVC in your project using Visual Studio templates, if y'all haven't follow these steps in your Visual Studio
1.Become to File->New->Project. Give a suitable proper name to the Application. Click OK.
2.Select MVC Template from information technology, and press OK
Now, Go to your View, Home->Alphabetize and add the <input> of file type, with a <button>
<input type="file" id="files" name="files" /> <input type="button" id="Upload" value="Upload" class="btn btn-primary" />
Add together the jQuery Code to upload files using FormData
<script> $(document).ready(function(){ $('#Upload').click(function () { var fileUpload = $("#files").get(0); var files = fileUpload.files; // Create a FormData object var fileData = new FormData(); // if in that location are multiple files , loop through each files for (var i = 0; i < files.length; i++) { fileData.suspend(files[i].name, files[i]); } // Adding more keys/values here if need fileData.append('Test', "Test Object values"); $.ajax({ url: '/Domicile/UploadFiles', //URL to upload files type: "Mail service", //equally we will be posting files and other method POST is used processData: false, //call back to set processData and ContentType to false, otherwise y'all may get an error contentType: faux, information: fileData, success: function (result) { alarm(result); }, error: function (err) { alert(err.statusText); } }); }); }); </script>
Note: remember to set processData and ContentType to faux, otherwise you may get an error
Then your consummate view lawmaking volition be every bit below
<br/> <input type="file" id="files" name="files" /> <input type="button" id="Upload" value="Upload" class="btn btn-principal" /> @section scripts{ <script> $(document).ready(function(){ $('#Upload').click(function () { var fileUpload = $("#files").go(0); var files = fileUpload.files; // Create a FormData object var fileData = new FormData(); // if in that location are multiple files , loop through each files for (var i = 0; i < files.length; i++) { fileData.append(files[i].name, files[i]); } // Calculation more keys/values here if demand fileData.append('Test', "Exam Object values"); $.ajax({ url: '/Dwelling/UploadFiles', //URL to upload files type: "POST", //as nosotros volition exist posting files and other method Mail service is used processData: false, //remember to set processData and ContentType to false, otherwise y'all may get an error contentType: false, data: fileData, success: part (result) { warning(event); }, error: role (err) { alert(err.statusText); } }); }); }); </script> }
At present, to get information in your C# controller, you need to create a ActionMethod
[HttpPost] public ActionResult UploadFiles() { if (Request.Files.Count > 0) { var files = Request.Files; //iterating through multiple file drove foreach (string str in files) { HttpPostedFileBase file = Asking.Files[str] as HttpPostedFileBase; //Checking file is bachelor to save. if (file != null) { var InputFileName = Path.GetFileName(file.FileName); var ServerSavePath = Path.Combine(Server.MapPath("~/Uploads/") + InputFileName); //Save file to server folder file.SaveAs(ServerSavePath); } } return Json("File Uploaded Successfully!"); } else { return Json("No files to upload"); } }
In the above code, you can to become value of fileData.append('Exam', "Examination Object values")
, you tin can employ Asking.Grade[position]
to become values, something like this
var value = Request.Class[0]; //for above lawmaking, output will be //'Test Object values'
Now, Let's run this projection in the Web browser and y'all will go output as below:
As I haven't added multiple attributes in file <input>, so I was able to select only one image, to select multiple files, y'all demand to only change the beneath line in HTML and you are washed
<input blazon="file" multiple name="files" id="files" />
Now, refresh your browser and attempt to select multiple files, output will be as below
Click "Upload", button and both of your files volition be sent to the controller, you can check it while debugging as below
As you can see in the above prototype, two files are sent to C# ActionMethod, and both will exist uploaded now.
Pure Javascript based File Uploading
If you lot don't desire to employ jQuery, then you can as well use Pure Javascript with XHR to pass file to C# Controller, hither is the sample code
Because you have below HTML
<form id="FileUploadForm"> <input id="fileInput" type="file" multiple> <input type="submit" value="Upload file" /> </form>
Then you tin can have Javascript code as beneath
document.getElementById('FileUploadForm').onsubmit = role () { var formdata = new FormData(); //FormData object var fileInput = document.getElementById('fileInput'); //Iterating through each files selected in fileInput for (i = 0; i < fileInput.files.length; i++) { //Appending each file to FormData object formdata.append(fileInput.files[i].name, fileInput.files[i]); } //Creating an XMLHttpRequest and sending var xhr = new XMLHttpRequest(); xhr.open('Post', '/Home/UploadFiles'); xhr.send(formdata); // se xhr.onreadystatechange = part () { if (xhr.readyState == 4 && xhr.status == 200) { //on success warning response alert(xhr.responseText); } } return false; }
We can utilize same C# Controller code for "UploadFiles" ActionMethod here.
You may too like:
jQuery File Upload with progress bar in ASP.Net MVC
File Upload in ASP.NET Cadre MVC (Single or Multiple File upload)
We are done here, If you have whatever questions or event feel free to ask it on questions section or comment beneath, cheers
Source: https://qawithexperts.com/article/asp.net/file-uploading-using-jquery-ajax-in-mvc-single-or-multiple-f/98
0 Response to "File Upload in Mvc Using Jquery Ajax"
Post a Comment