An overview,
Use of FormData objects:
- Use key-value pairs to simulate a series of form controls: combine the name and value of all the elements in a form into a queryString.
- Asynchronously upload binary files.
Second, the use of
-
Create an empty object instance.
var myform = new FormData(); Copy the code
-
Initialize using an existing form
<form id="myForm" action="" method="post"> <input type="text" name="name">The name<input type="password" name="psw">password<input type="submit" value="Submit"> </form> Copy the code
You can use this form element as an initialization parameter to instantiate the FormData object
// Get an existing form from the page var form = document.getElementById("myForm"); // Use the form to initialize var formData = new FormData(form); // We can access the fields in the form by name var name = formData.get("name"); // Get the name var psw = formData.get("psw"); // Get the password // You can also add other data based on this formData.append("token"."kshdfiwi3rh"); Copy the code
-
The API operations
Value 3.1,
formData.get("name"); // Get the first value with key as name formData.getAll("name"); // Return an array of all values whose key is name Copy the code
3.2. Add data
Append (Key,value) is used to add data. If the specified key does not exist, a new data is added. If the key does exist, the data is appended to the end
formData.append("k1"."v1"); formData.append("k1"."v2"); formData.append("k1"."v1"); formData.get("k1"); // "v1" formData.getAll("k1"); // ["v1","v2","v1"] Copy the code
3.3. Set and modify data
Set (key,value) to set the data to be modified. If the specified key does not exist, a new key is added. If the specified key does exist, the corresponding value is changed
formData.append("k1"."v1"); formData.set("k1"."1"); formData.getAll("k1"); / / / "1" Copy the code
3.4 check whether the key exists
Check whether the key-value pair corresponding to the key exists by checking has(key). The return value is true if the key exists, and false if the key does not exist
formData.append("k1"."v1"); formData.append("k2".null); formData.has("k1"); // true formData.has("k2"); // true formData.has("k3"); // false Copy the code
3.5. Delete data
Delete the key pair corresponding to the key by delete(key)
formData.append("k1"."v1"); formData.append("k1"."v2"); formData.append("k1"."v1"); formData.delete("k1"); formData.getAll("k1"); / / [] Copy the code
3.6, traverse
3.6.1. Each call to next() returns one piece of data, the order of which is determined by the order in which it was added
3.6.2 An object is returned. If its done attribute is true, it indicates that all data has been traversed. This can also be used as a basis for judgment
3.6.3. The value property of the returned object stores a pair of keys/values in the form of an array with subscript 0 for key and subscript 1 for value. If a key value corresponds to multiple values, multiple pairs of keys/values will be returned
formData.append("k1"."v1"); formData.append("k1"."v2"); formData.append("k2"."v1"); var i = formData.entries(); i.next(); // {done:false, value:["k1", "v1"]} i.next(); // {done:fase, value:["k1", "v2"]} i.next(); // {done:fase, value:["k2", "v1"]} i.next(); // {done:true, value:undefined} Copy the code
-
Sends data to the background
<! - HTML part -- -- > <form action=""> <label for="">Name:<input type="text" name="name"> </label> <label for="">File:<input id="file" type="file" name="file"> </label> <label for=""> <input type="button" value="Save"> </label> </form> Copy the code
4.1. Native Ajax
// Upload native JS files // Get the button var btn = document.querySelector('[type=button]'); // Bind events btn.onclick = function () { // Get the input tag var file = document.querySelector('[type=file]'); // Create a FormData object var formData = new FormData(); // Get the file in the input tag. Note: You can select more than one file in the input tag formData.append('upload', file.files[0]); // Create an XMLHttpRequest and use this to send data var xhr = new XMLHttpRequest; /* Initializes the HTTP request parameters (request mode, URL, sync or not)*/ xhr.open('post'.'file.php'); /* xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); Set the contentType */ of the request header // Monitor the upload progress xhr.upload.onprogress = function (ev) { // Event object // console.log(ev); var percent = (ev.loaded / ev.total) * 100 + The '%'; console.log(percent); progress.style.width = percent; } xhr.send(formData); xhr.onreadystatechange = function () { //status a status of 200 indicates that the request is successful, and readyState 4 indicates that the object is delivered or ready if(xhr.readyState == 4 && xhr.status == 200) {}}}Copy the code
4.2, jq ajax
// Bind commit events function upload() { // Get the form element var f = document.getElementById("myForm"); // Use form elements to construct FromData var myform = new FormData(f); $.ajax({ url: "/Library/test/upload".type: "post".dataType: "json".data: myform, cache: false./ / no cache processData: false.// jQuery does not process the sent data contentType: false.// jQuery does not set the content-type request header success: function (data) { console.log(data); }}); }Copy the code
4.3, axios
// No NEED for HTML block mode // Note: input type="file"; File Chooser dialog can only be shown with a user activation. function upImg(){ const inp = document.createElement("input"); const _this = this inp.type = "file"; inp.click(); inp.onchange = function(e) { console.log(e.target.files[0]); let params = new FormData(); // Create a form object params.append("file", e.target.files[0]); _this.$axios.post("/api/Base/uploadImg", params).then(res= > { console.log(res) }).catch(err= > { console.log(err); }); }}Copy the code