Asp.net How Upload a File to Server With Jquery
There are many ways to upload files on server, only in this I volition give you example to upload file using jQuery Ajax, if yous want to utilise whatsoever eternal plugin like Dropzone.js you can read "File uploading using DropZone js & HTML5 in MVC" or if yous want to Upload file using HTML.BeginForm, you can read my commodity "Uploading Files in ASP.Net MVC C# (Single & Multiple Files)"
Before we proceed further I will like to that about the way we will upload the files using jQuery Ajax, so basically we will exist using FormData object.
Almost FormData
The FormData interface provides a way to easily construct a set of key/value pairs representing class fields and their values, which tin can then exist easily sent using the XMLHttpRequest.ship() method.Information technology uses the same format a grade would use if the encoding type were set to "multipart/form-data".
FormData methods:
- FormData.suspend(): Appends a new value onto an existing fundamental within a
FormDataobject, or adds the key if it does not already exist. - FormData.delete():Deletes a key/value pair from a
FormDataobject. - FormData.entries(): Returns an
iteratorallowing to get through all key/value pairs contained in this object. - FormData.get(): It returns value of given key within FormData object.
- FromData.has(): Information technology returns a Boolean value whether a given key is present inside object.
- FormData.keys(): It helps to become all keys nowadays inside object.
- FormData.set(): It helps to prepare/update a new value to existing keys or add new primal-value pair if doesn't be.
- FormData.values():Returns an iterator assuasive to go through all values of the key/value pairs contained in this object.
You tin can read more about it from this reference
Compatibility and detection
You can verify if the client browser back up the FormData or not using the beneath code
function supportAjaxUploadWithProgress() { render supportFileAPI() && supportAjaxUploadProgressEvents() && supportFormData(); function supportFileAPI() { var fi = document.createElement('INPUT'); fi.type = 'file'; return 'files' in fi; }; office supportAjaxUploadProgressEvents() { var xhr = new XMLHttpRequest(); return !! (xhr && ('upload' in xhr) && ('onprogress' in xhr.upload)); }; role supportFormData() { return !! window.FormData; } } Elementary way to submit the complete HTML form using FormData
FormData gives united states 2 means to interface with information technology. The offset and simplest is: get a reference to the form element and pass it to the FormData constructor, like and then:
var form = document.getElementById('form-id'); var formData = new FormData(form); Another manner is to call
var xhr = new XMLHttpRequest(); // any event handlers here... xhr.open('POST', '/upload/path', true); xhr.send(formData); Uploading Files in MVC using jQuery AJAX FormData
I presume, yous have already created the basic structure of MVC in your projection using Visual Studio templates, if yous haven't follow these steps in your Visual Studio
i.Go to File->New->Project. Give a suitable proper name to the Awarding. Click OK.
2.Select MVC Template from it, and press OK
Now, Go to your View, Dwelling house->Index and add together the <input> of file blazon, with a <button>
<input type="file" id="files" name="files" /> <input type="button" id="Upload" value="Upload" form="btn btn-primary" /> Add together the jQuery Lawmaking to upload files using FormData
<script> $(document).ready(office(){ $('#Upload').click(office () { var fileUpload = $("#files").become(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]); } // Adding more than keys/values here if need fileData.suspend('Test', "Test Object values"); $.ajax({ url: '/Home/UploadFiles', //URL to upload files blazon: "Mail", //as we will exist posting files and other method POST is used processData: fake, //remember to set processData and ContentType to faux, otherwise you may go an error contentType: false, data: fileData, success: part (consequence) { alarm(issue); }, mistake: function (err) { alarm(err.statusText); } }); }); }); </script> Note: remember to set processData and ContentType to imitation, otherwise yous may get an fault
So your consummate view code will exist equally below
<br/> <input type="file" id="files" name="files" /> <input type="button" id="Upload" value="Upload" class="btn btn-primary" /> @section scripts{ <script> $(certificate).set(part(){ $('#Upload').click(part () { var fileUpload = $("#files").get(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].proper name, files[i]); } // Adding more keys/values hither if demand fileData.suspend('Test', "Test Object values"); $.ajax({ url: '/Home/UploadFiles', //URL to upload files type: "POST", //equally nosotros will be posting files and other method Postal service is used processData: false, //retrieve to set processData and ContentType to false, otherwise yous may get an fault contentType: false, data: fileData, success: role (outcome) { alert(outcome); }, mistake: role (err) { warning(err.statusText); } }); }); }); </script> } Now, to get information in your C# controller, you need to create a ActionMethod
[HttpPost] public ActionResult UploadFiles() { if (Asking.Files.Count > 0) { var files = Request.Files; //iterating through multiple file collection foreach (string str in files) { HttpPostedFileBase file = Request.Files[str] as HttpPostedFileBase; //Checking file is available to save. if (file != null) { var InputFileName = Path.GetFileName(file.FileName); var ServerSavePath = Path.Combine(Server.MapPath("~/Uploads/") + InputFileName); //Save file to server binder file.SaveAs(ServerSavePath); } } render Json("File Uploaded Successfully!"); } else { return Json("No files to upload"); } } In the above code, you can to get value of fileData.append('Exam', "Test Object values"), you tin use Request.Form[position] to become values, something like this
var value = Request.Form[0]; //for above code, output will be //'Examination Object values' Now, Let's run this project in the Spider web browser and you lot will get output as below:
As I haven't added multiple attributes in file <input>, so I was able to select just one image, to select multiple files, y'all need to but change the below line in HTML and you are washed
<input type="file" multiple proper name="files" id="files" /> At present, refresh your browser and effort to select multiple files, output will be as beneath
Click "Upload", button and both of your files will exist sent to the controller, y'all can cheque it while debugging every bit below
As you lot can come across in the above epitome, two files are sent to C# ActionMethod, and both will exist uploaded now.
Pure Javascript based File Uploading
If yous don't want to use jQuery, then you tin also utilize Pure Javascript with XHR to pass file to C# Controller, hither is the sample code
Considering yous take below HTML
<form id="FileUploadForm"> <input id="fileInput" blazon="file" multiple> <input type="submit" value="Upload file" /> </form> Then you can take Javascript code as below
document.getElementById('FileUploadForm').onsubmit = function () { 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('Postal service', '/Home/UploadFiles'); xhr.send(formdata); // se xhr.onreadystatechange = function () { if (xhr.readyState == iv && xhr.status == 200) { //on success warning response alarm(xhr.responseText); } } render simulated; } We can use same C# Controller code for "UploadFiles" ActionMethod here.
You lot may also like:
jQuery File Upload with progress bar in ASP.Cyberspace MVC
File Upload in ASP.Internet Core MVC (Single or Multiple File upload)
Nosotros are done here, If you have any questions or issue feel free to ask information technology on questions section or comment below, thanks
belsteadquinginotted.blogspot.com
Source: https://qawithexperts.com/article/asp.net/file-uploading-using-jquery-ajax-in-mvc-single-or-multiple-f/98
0 Response to "Asp.net How Upload a File to Server With Jquery"
Post a Comment