FormData
What is the FormData object?
FormData
The object is an API provided by HTML5, which supports uploading binary files and large text data. When uploading images in the front end, we usually use FormData
the object to construct the form data and send it to the back end.
Why can FormData pass pictures?
Traditional forms can only contain key-value pairs and cannot contain binary data. However, FormData
objects can contain binary data, such as picture files. When we use append()
the method FormData
to add a file object to the object, the file will be automatically converted into binary data and added to the form data
When uploading images, since the image data is usually large, it cannot be placed in the URL. If you use a GET request to transfer image data, you need to convert the image data into Base64 encoding format, which will cause data redundancy and low transmission efficiency. Therefore, we usually use POST requests to pass image data, and in POST requests, FormData
objects can include image data in the request body.
Some basic operating methods and procedures of FormData
Create a FormData object: You can new FormData()
create a new FormData object using the method
const formData = new FormData();
Adding values to the FormData object: You can use append()
methods to add new key-value pairs to the FormData object. This method accepts two parameters, the first parameter is the key name, and the second parameter is the key value
formData.append('username', 'Tom');
formData.append('password', '123456');
Adding Blob objects is also supported
formData.append('file', blob, 'example.png');
Delete the value in the FormData object: You can use delete()
the method to delete the specified key name and its corresponding key value from the FormData object.
formData.delete('username');
Get the value in the FormData object: You can use get()
the method to get the key value of the specified key name from the FormData object.
const username = formData.get('username');
application/json、application/x-www-form-urlencoded、form-data
What are the three formats application/json, application/x-www-form-urlencoded and form-data?
These three formats are common formats used to transfer data between clients and servers
what's the effect
application/json
It is a data transfer format used to transfer structured data between clients and servers. It uses JSON (JavaScript Object Notation) as the representation of data and serializes the data into strings for transmission. The JSON format is readable, easy to parse and generate, and is widely supported and used in various programming languages and platforms.
application/x-www-form-urlencoded
It is a common form data transmission format. It encodes form data in the form of key-value and represents it using URL encoding format. When the client sends a request, the form data is encoded into a string and the key-value pairs for each field are concatenated and &
separated by symbols, key1=value1&key2=value2
e.g. This format is mainly used for HTML form submissions
multipart/form-data
Is a format used for uploading files and form data. It can transmit binary files and other form data at the same time, and is suitable for scenarios where files need to be uploaded.
What is the difference between the three?
Data structure:application/json
Use JSON format to represent data, which can transmit complex and nested data structures; application/x-www-form-urlencoded
and multipart/form-data
use key-value pairs to represent data, which is suitable for transmitting simpler data structures.
Applicable scenarios:application/json
Suitable for transmitting structured data, often used in RESTful APIs; application/x-www-form-urlencoded
suitable for form submission and simpler data transmission; multipart/form-data
suitable for file upload and simultaneous transmission of files and form data.
Data encoding method:application/json
Use JSON format for data encoding; application/x-www-form-urlencoded
use URL encoding format for data encoding; multipart/form-data
use delimiters and multiple parts for data encoding.
File upload support:application/json
and application/x-www-form-urlencoded
does not directly support file upload, but multipart/form-data
can support file upload.
Blob URL with base64
what is
blob:http://127.0.0.1:5500/d96d1b24-0a77-4010-b6c0-4d44ef95e485 Blob URL
Blob URL is a special URL format used to reference binary data. It points to a block of binary data (Blob object) in the browser, which can be an image, audio, video, or other file type. The format of a Blob URL is blob:<origin>/<unique-id>
, where <origin>
represents the source of the URL and <unique-id>
is a unique identifier
Base64 is an encoding used to convert binary data into plain text strings. It processes binary data in groups of three bytes and converts each group into a four-character Base64 string.
what's the difference
Blob URLs provide direct access to binary data without encoding or decoding.
Base64 encoded data can be easily transmitted and stored, but requires encoding and decoding before use
canvas converts the content into blob and then uploads it to the background
method one,
let canvas = $('#canvas')
canvas.toBlob(blob => {
const reader = new FileReader();
reader.readAsDataURL(blob);
reader.onload = function() {
const file = new File([blob], 'fileName.jpg', { type: blob.type });
// 现在,可以将生成的 file 对象作为参数传递到后台了
uploadFile(file);
}
});
function uploadFile(file) {
const formData = new FormData();
formData.append('file', file);
$.ajax({
url: '/upload',
type: 'POST',
data: formData,
processData: false,
contentType: false,
success: function(response) {
console.log(response);
},
error: function(xhr, status, error) {
console.error(error);
}
});
}
processData: false, contentType: false, what does it do?
processData: false
: By default, when using jQuery.ajax()
or $.ajax()
sending a POST request, jQuery will convert the data into query string format (key=value&key=value) and send it to the server. However, when you need to send special types of data such as FormData, Blob, ArrayBuffer, etc., you can processData
set it to false
tell jQuery not to process the data. This will keep the format of the original data so it can be sent to the server correctly
contentType: false
: By default, jQuery automatically sets headers based on the data type when using jQuery.ajax()
or sending a POST request . However, when you send the FormData object, you need to set to so that the browser automatically sets the correct header (usually )$.ajax()
Content-Type
contentType
false
Content-Type
multipart/form-data
Method Two,
canvas.toBlob((blob) => {
const formData = new FormData();
formData.append('file', blob, 'canvas.jpg');
formData.append('name', 'My Canvas Image');
$.ajax({
url: '/upload',
type: 'POST',
data: formData,
processData: false,
contentType: false,
success: function (response) {
console.log(response);
},
error: function (xhr, status, error) {
console.error(error);
}
});
});