About FormData
XMLHttpRequest Level 2 has added a new interface --- FormData
Using FormData object, you can simulate a series of form controls with some key-value pairs through js. You can use the send( ) method of XMLHttpRequest to submit forms asynchronously. Compared with ordinary ajax, the biggest advantage of using FormData is that it can upload binary files asynchronously.
FormData object
The FormData object can form a queryString of the name and value of all form elements and submit it to the background. Using FormData objects can reduce the workload of stitching queryString when submitting using ajax
queryString is a query string, http query string is from url? The following value specifies
When the form on the page sends requested data to the page in GET mode (if the data contains unsafe characters, the browser first converts it into hexadecimal characters and then transmits it, such as when the space is converted to %20), the web server places the requested data into an environment variable called QUERY_STRING. The Request.QueryString method is to take out the corresponding value from this environment variable and restore the characters converted to hexadecimal.
Upload files and pictures using FormData
Create a FormData empty object, and then add key/value using the append method
var formdata=new FormData(); formdata.append ("name" , "Zhang San");If there is already a Form form, get the form object and pass it into the FormData object as a parameter
<!DOCTYPE html><html><head> <meta charset="utf-8"/> <title></title></head><body> <form name="form1" id="form1"> <input id="file" type="file" name="name"></input> </form> <script type="text/javascript"> var form=document.getElementById("form1"); var formdata=new FormData(form); </script></body></html>You can continue to add new key-value pairs based on existing form data.
var formdata=new FormData(); formdata.append ("age" , "21");Upload files using FormData objects
var formdata=new FormData($("#form1").[0]);//get file method one//var formdata=new FormData( ); //formdata.append("file" , $("#file")[0].files[0]);//get file method two$.ajax({ type : 'post', url : '#', data : formdata, cache : false, processData : false, // does not process the sent data, because the data value is a Formdata object, no processing of the data is required. contentType : false, // Do not set the Content-type request header success : function(){} error : function(){ } })The above is the complete description of the method of using FormData to upload files and pictures in JS introduced to you by the editor. I hope it will be helpful to everyone. If you have any questions, please leave me a message!