Using FormData to upload files and images in JS,
About FormData
XMLHttpRequest Level 2 adds a new interface ---- FormData
The FormData object can be used to simulate a series of form controls using some key-value pairs in js. The send () method of XMLHttpRequest can be used to submit forms asynchronously compared with common ajax, the biggest advantage of using FormData is that binary files can be uploaded asynchronously.
FormData object
FormData object, which can combine the name and value of all form elements into a queryString and submit it to the background. When ajax is used for submission, using the FormData object can reduce the amount of work required to splice queryString.
QueryString is the query string, and the http query string is in the url? Specify the value following
When the form on the page sends request data to the page in the GET mode (if the data contains insecure characters, the browser first converts the data to hexadecimal characters before transmission, if a space is converted to % 20), the web server puts the request data in an environment variable named QUERY_STRING. The Request. QueryString method extracts the corresponding value from this environment variable and restores the value to a hexadecimal character.
Use FormData to upload files and Images
Create a FormData empty object and use the append method to add key/value
Var formdata = new FormData (); formdata. append ("name", "James ");
If there is already a Form, get the form object and pass in the FormData object as the parameter
<!DOCTYPE html>
You can add new key-value pairs based on existing form data.
var formdata=new FormData(); formdata.append ("age" , "21");
Upload a file using the FormData object
Var formdata = new FormData ($ ("# form1 "). [0]); // obtain file method 1 // var formdata = new FormData (); // formdata. append ("file", $ ("# file") [0]. files [0]); // method 2 $. ajax ({type: 'post', url: '#', data: formdata, cache: false, processData: false, // do not process sent data, because the data value is a Formdata object, you do not need to process the data contentType: false, // do not set the Content-type Request Header success: function () {} error: function () {}})
The above is a full description of how to use FormData to upload files and images in Javascript. I hope it will help you. If you have any questions, please leave a message!