Today I will give you a detailed introduction to the FormData object. Next, create a FormData object from scratch, and then add key values to the object through the append() method. Please see the case
var formData = new FormData(); formData.append("username", "Groucho"); formData.append("accountnum", 123456); // number 123456 is immediately converted to a string "123456" // HTML file input, chosen by user formData.append("userfile", fileInputElement.files[0]); // JavaScript file-like object var content = '<a id="a"><b id="b">hey!</b></a>'; // the body of the new file... var blob = new Blob([content], { type: "text/xml"}); formData.append("webmasterfile", blob); var request = new XMLHttpRequest(); request.open("POST", "http://foo.com/submitform.php");
Note: Field" userfile" and "webmasterfile" both include files (file). The number assigned to the field "accountnum" is directly converted into a string by the FormData.append() method (the value of the field may be a Blob, File, or a string: if the value is both If it is not a Blob or a File, the value will be converted to a string).
This example creates a FormData instance that contains the fields "username", "accountnum", "userfile" and "webmasterfile", and then uses the send() method of the XMLHttpRequest object to send the form data. The field "webmasterfile" is a Blob. A Blob object represents the raw data of a file object. But the data represented by Blob does not have to be data in the native JavaScript format. The file interface is based on Blob, inheriting Blob functions and expanding its support for user file systems. To construct a Blob, call Blob()Constructor.
Get a FormData object from a HTML form
In order to obtain a FormData object containing existing form data, you need to specify the form element when creating the FormData object.
var formData = new FormData(someFormElement);
Like the following:
var formElement = document.querySelector("form"); var request = new XMLHttpRequest(); request.open("POST", "submitform.php"); request.send(new FormData(formElement));
You can also add additional data after obtaining the FormData object, like the following:
var formElement = document.querySelector("form"); var formData = new FormData(formElement); var request = new XMLHttpRequest(); request.open("POST", "submitform.php"); formData.append("serialnumber", serialNumber++); request.send(formData);
In this way you can add additional data before sending Add additional information, not necessarily edited by the user.
3. Use the FormData object to send files
You can use FormData to send files. Simply include an element in the