FormData is a detailed introduction and usage https://developer.mozilla.org/zh ... ng_FormData_Objects
The methods and events of FormData are already very clear there, so I won't waste time on them here. This article mainly explains the use of FormData objects and asynchronous file uploads.
The FormData object allows us to organize a collection of key-value pairs sent using the XMLHttpRequest object. It is primarily used to send form data, but can be used independently of data transferred using forms.
1. Create a FormData object from scratch
You can create your own FormData object and then add key-value pairs to the object via the append() method, like this:
Note: Both the fields "userfile" and "webmasterfile" contain files. The number assigned to the field "accountnum" is directly converted to a string by the FormData.append() method (the value of the field may be a blob, file, or a string: if the value is neither a blob nor a file, the value is converted to a string). This example creates a FormData instance with the fields "username", "accountnum", "userfile" and "webmasterfile", and then uses the XMLHttpRequest object's send() method 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 the blob does not have to be in the javascript native format. The file interface is based on blobs, inheriting blob functionality and expanding its support for user file systems. To build a blob, the Blob() constructor can be called.
2. Get a FormData object from an 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.
Like this:
You can also add additional data after getting the FormData object, like this:
This allows you to add additional information before sending, not necessarily user-edited.
3. Use the FormData object to send the file
You can use FormData to send files. A simple <form>middle can <input>include an element:
You can then use the following code to send it:
You can also add a File or Blob directly to the FormData object, like this:
When using the append() method, a third parameter may be used to send the file name (sent to the server via the Content-Disposition header). If the third parameter is not specified or this parameter is not supported, the third parameter defaults to "blob".
If you set the correct options, you can also use it with jQuery:
|