Jquery Ajax File Upload Example Asp.net Mvc
There are many ways to upload files on server, just in this I will give you example to upload file using jQuery Ajax, if you want to use whatever 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, yous can read my article "Uploading Files in ASP.NET MVC C# (Unmarried & Multiple Files)"
Before we proceed further I will similar to that most the way we will upload the files using jQuery Ajax, so basically we will exist using FormData object.
About FormData
The FormData interface provides a mode to easily construct a fix of key/value pairs representing form fields and their values, which can and then be easily sent using the XMLHttpRequest.send() method.It uses the same format a form would use if the encoding type were prepare to "multipart/form-data".
FormData methods:
- FormData.append(): Appends a new value onto an existing key inside a
FormDataobject, or adds the central if information technology does non already exist. - FormData.delete():Deletes a key/value pair from a
FormDataobject. - FormData.entries(): Returns an
iteratorassuasive to go through all central/value pairs contained in this object. - FormData.go(): 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(): Information technology helps to get all keys nowadays inside object.
- FormData.set(): Information technology helps to set/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 primal/value pairs contained in this object.
You tin read more about it from this reference
Compatibility and detection
Y'all tin can verify if the client browser support the FormData or not using the below code
function supportAjaxUploadWithProgress() { return supportFileAPI() && supportAjaxUploadProgressEvents() && supportFormData(); role supportFileAPI() { var fi = document.createElement('INPUT'); fi.type = 'file'; return 'files' in fi; }; part supportAjaxUploadProgressEvents() { var xhr = new XMLHttpRequest(); render !! (xhr && ('upload' in xhr) && ('onprogress' in xhr.upload)); }; function supportFormData() { render !! window.FormData; } } Elementary way to submit the complete HTML form using FormData
FormData gives us 2 ways to interface with it. The start and simplest is: go a reference to the form element and laissez passer it to the FormData constructor, like and so:
var course = document.getElementById('form-id'); var formData = new FormData(form); Another way is to phone call
var xhr = new XMLHttpRequest(); // whatsoever event handlers hither... xhr.open('POST', '/upload/path', true); xhr.send(formData); Uploading Files in MVC using jQuery AJAX FormData
I assume, y'all have already created the bones structure of MVC in your projection using Visual Studio templates, if you oasis't follow these steps in your Visual Studio
1.Go to File->New->Projection. Requite a suitable name to the Application. Click OK.
2.Select MVC Template from it, and press OK
Now, Go to your View, Home->Index and add together the <input> of file type, with a <button>
<input type="file" id="files" name="files" /> <input type="push" id="Upload" value="Upload" class="btn btn-primary" /> Add together the jQuery Code to upload files using FormData
<script> $(certificate).ready(part(){ $('#Upload').click(function () { var fileUpload = $("#files").get(0); var files = fileUpload.files; // Create a FormData object var fileData = new FormData(); // if at that place are multiple files , loop through each files for (var i = 0; i < files.length; i++) { fileData.append(files[i].name, files[i]); } // Adding more keys/values here if need fileData.append('Test', "Test Object values"); $.ajax({ url: '/Home/UploadFiles', //URL to upload files blazon: "POST", //equally we will be posting files and other method Mail is used processData: faux, //think to prepare processData and ContentType to false, otherwise you may get an fault contentType: false, data: fileData, success: role (result) { alarm(effect); }, error: function (err) { alert(err.statusText); } }); }); }); </script> Annotation: think to set processData and ContentType to false, otherwise you may go an error
So your consummate view code will be as beneath
<br/> <input blazon="file" id="files" name="files" /> <input type="push button" id="Upload" value="Upload" class="btn btn-primary" /> @section scripts{ <script> $(document).ready(function(){ $('#Upload').click(function () { var fileUpload = $("#files").become(0); var files = fileUpload.files; // Create a FormData object var fileData = new FormData(); // if there are multiple files , loop through each files for (var i = 0; i < files.length; i++) { fileData.append(files[i].name, files[i]); } // Adding more than keys/values here if need fileData.append('Exam', "Test Object values"); $.ajax({ url: '/Home/UploadFiles', //URL to upload files type: "Postal service", //as we will be posting files and other method POST is used processData: false, //recall to prepare processData and ContentType to false, otherwise y'all may go an error contentType: false, information: fileData, success: function (event) { alarm(result); }, error: office (err) { alarm(err.statusText); } }); }); }); </script> } Now, to get information in your C# controller, you lot demand to create a ActionMethod
[HttpPost] public ActionResult UploadFiles() { if (Request.Files.Count > 0) { var files = Request.Files; //iterating through multiple file collection foreach (cord str in files) { HttpPostedFileBase file = Asking.Files[str] as HttpPostedFileBase; //Checking file is available to save. if (file != aught) { 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 { render Json("No files to upload"); } } In the in a higher place lawmaking, y'all tin can to get value of fileData.suspend('Test', "Exam Object values"), you tin can employ Asking.Form[position] to go values, something like this
var value = Request.Grade[0]; //for to a higher place code, output volition be //'Test Object values' Now, Permit'due south run this project in the Spider web browser and you will become output as below:
Every bit I haven't added multiple attributes in file <input>, and then I was able to select only i epitome, to select multiple files, y'all demand to just change the below line in HTML and you are done
<input type="file" multiple proper name="files" id="files" /> Now, refresh your browser and try to select multiple files, output will be every bit beneath
Click "Upload", button and both of your files volition exist sent to the controller, you tin check it while debugging equally below
As you tin can run into in the to a higher place image, two files are sent to C# ActionMethod, and both will be uploaded now.
Pure Javascript based File Uploading
If yous don't want to use jQuery, so y'all can also use Pure Javascript with XHR to laissez passer file to C# Controller, here is the sample code
Because you have below HTML
<form id="FileUploadForm"> <input id="fileInput" blazon="file" multiple> <input type="submit" value="Upload file" /> </form> And so you lot can accept Javascript code equally below
document.getElementById('FileUploadForm').onsubmit = role () { var formdata = new FormData(); //FormData object var fileInput = certificate.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.transport(formdata); // se xhr.onreadystatechange = part () { if (xhr.readyState == 4 && xhr.status == 200) { //on success alert response alert(xhr.responseText); } } render false; } Nosotros can use same C# Controller code for "UploadFiles" ActionMethod here.
You may also like:
jQuery File Upload with progress bar in ASP.Internet MVC
File Upload in ASP.NET Core MVC (Single or Multiple File upload)
Nosotros are done here, If you have whatsoever questions or result feel free to inquire it on questions section or annotate below, thanks
hudsonthenecolasty1936.blogspot.com
Source: https://qawithexperts.com/article/asp.net/file-uploading-using-jquery-ajax-in-mvc-single-or-multiple-f/98
0 Response to "Jquery Ajax File Upload Example Asp.net Mvc"
Post a Comment