Javascript if File Uploaded Pass to Form
In that location are many ways to upload files on server, but in this I will requite you example to upload file using jQuery Ajax, if you desire to use whatever eternal plugin similar 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 can read my commodity "Uploading Files in ASP.Net MVC C# (Single & Multiple Files)"
Before we proceed further I will like to that almost the way 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 fix of key/value pairs representing grade fields and their values, which can then be hands sent using the XMLHttpRequest.send()
method.Information technology uses the same format a grade would apply if the encoding type were set to "multipart/form-data"
.
FormData methods:
- FormData.append(): Appends a new value onto an existing key inside a
FormData
object, or adds the key if it does non already exist. - FormData.delete():Deletes a cardinal/value pair from a
FormData
object. - FormData.entries(): Returns an
iterator
allowing to go through all key/value pairs independent in this object. - FormData.get(): It returns value of given cardinal 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 cardinal-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 than nearly it from this reference
Compatibility and detection
Y'all can verify if the customer browser support the FormData or not using the below code
function supportAjaxUploadWithProgress() { render supportFileAPI() && supportAjaxUploadProgressEvents() && supportFormData(); function supportFileAPI() { var fi = document.createElement('INPUT'); fi.type = 'file'; render 'files' in fi; }; role supportAjaxUploadProgressEvents() { var xhr = new XMLHttpRequest(); render !! (xhr && ('upload' in xhr) && ('onprogress' in xhr.upload)); }; office supportFormData() { render !! window.FormData; } }
Simple mode to submit the complete HTML form using FormData
FormData
gives the states two ways to interface with it. The first and simplest is: get a reference to the form
element and pass it to the FormData
constructor, similar so:
var form = document.getElementById('form-id'); var formData = new FormData(form);
Another way is to call
var xhr = new XMLHttpRequest(); // any event handlers here... xhr.open('Mail', '/upload/path', true); xhr.ship(formData);
Uploading Files in MVC using jQuery AJAX FormData
I assume, yous have already created the basic construction 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->Project. Give a suitable name to the Application. Click OK.
2.Select MVC Template from information technology, and press OK
Now, Go to your View, Home->Index and add together the <input> of file blazon, with a <button>
<input type="file" id="files" proper noun="files" /> <input type="button" id="Upload" value="Upload" course="btn btn-primary" />
Add 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 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('Test', "Test Object values"); $.ajax({ url: '/Home/UploadFiles', //URL to upload files type: "POST", //every bit we volition exist posting files and other method POST is used processData: imitation, //remember to set processData and ContentType to false, otherwise you may get an error contentType: false, information: fileData, success: function (result) { alert(upshot); }, mistake: function (err) { warning(err.statusText); } }); }); }); </script>
Note: think to ready processData and ContentType to fake, otherwise you lot may get an error
So your complete view lawmaking will be as below
<br/> <input type="file" id="files" name="files" /> <input blazon="button" id="Upload" value="Upload" grade="btn btn-main" /> @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 hither if need fileData.append('Test', "Exam Object values"); $.ajax({ url: '/Home/UploadFiles', //URL to upload files type: "POST", //as we will be posting files and other method Post is used processData: faux, //recall to set up processData and ContentType to false, otherwise you may get an error contentType: fake, information: fileData, success: part (result) { alert(result); }, mistake: function (err) { warning(err.statusText); } }); }); }); </script> }
Now, to get data 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 collection foreach (cord str in files) { HttpPostedFileBase file = Request.Files[str] as HttpPostedFileBase; //Checking file is bachelor to save. if (file != nada) { var InputFileName = Path.GetFileName(file.FileName); var ServerSavePath = Path.Combine(Server.MapPath("~/Uploads/") + InputFileName); //Save file to server binder file.SaveAs(ServerSavePath); } } return Json("File Uploaded Successfully!"); } else { return Json("No files to upload"); } }
In the above code, you can to go value of fileData.append('Test', "Test Object values")
, y'all can use Request.Course[position]
to get values, something like this
var value = Request.Form[0]; //for above code, output volition exist //'Exam Object values'
Now, Let's run this project in the Web browser and you will become output as beneath:
As I haven't added multiple attributes in file <input>, and so I was able to select only one image, to select multiple files, you need to simply modify the below line in HTML and you are done
<input type="file" multiple proper noun="files" id="files" />
Now, refresh your browser and try to select multiple files, output will be as below
Click "Upload", button and both of your files volition exist sent to the controller, you lot can bank check information technology while debugging equally below
As you lot tin can see in the above prototype, two files are sent to C# ActionMethod, and both will be uploaded now.
Pure Javascript based File Uploading
If you don't want to use jQuery, and so y'all can also use Pure Javascript with XHR to laissez passer file to C# Controller, here is the sample code
Considering you lot have below HTML
<form id="FileUploadForm"> <input id="fileInput" type="file" multiple> <input type="submit" value="Upload file" /> </form>
Then y'all can have Javascript code as below
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 up('POST', '/Home/UploadFiles'); xhr.send(formdata); // se xhr.onreadystatechange = function () { if (xhr.readyState == 4 && xhr.status == 200) { //on success alert response alert(xhr.responseText); } } render imitation; }
We can use same C# Controller code for "UploadFiles" ActionMethod here.
You may besides like:
jQuery File Upload with progress bar in ASP.NET MVC
File Upload in ASP.Cyberspace Cadre MVC (Single or Multiple File upload)
We are done here, If yous have any questions or upshot feel free to ask it on questions section or comment below, thanks
Source: https://qawithexperts.com/article/asp.net/file-uploading-using-jquery-ajax-in-mvc-single-or-multiple-f/98
0 Response to "Javascript if File Uploaded Pass to Form"
Post a Comment