多部分的主体
将数据发送为 multipart/form-data
¥Posting data as multipart/form-data
使用表单数据 API
¥Using FormData API
浏览器
¥Browser
const form = new FormData();
form.append('my_field', 'my value');
form.append('my_buffer', new Blob([1,2,3]));
form.append('my_file', fileInput.files[0]);
axios.post('https://example.com', form)
使用内部 Axios 序列化器和相应的速记方法可以实现相同的结果:
¥The same result can be achieved using the internal Axios serializer and corresponding shorthand method:
axios.postForm('https://httpbin.org/post', {
my_field: 'my value',
my_buffer: new Blob([1,2,3]),
my_file: fileInput.files // FileList will be unwrapped as sepate fields
});
HTML 表单可以直接作为请求负载传递
¥HTML form can be passes directly as a request payload
Node.js
import axios from 'axios';
const form = new FormData();
form.append('my_field', 'my value');
form.append('my_buffer', new Blob(['some content']));
axios.post('https://example.com', form)
由于 node.js 当前不支持从文件创建 Blob
,因此你可以使用第三方包来实现此目的。
¥Since node.js does not currently support creating a Blob
from a file, you can use a third-party package for this purpose.
import {fileFromPath} from 'formdata-node/file-from-path'
form.append('my_field', 'my value');
form.append('my_file', await fileFromPath('/foo/bar.jpg'));
axios.post('https://example.com', form)
对于早于 v1.3.0
的 Axios,你必须导入 form-data
包。
¥For Axios older than v1.3.0
you must import form-data
package.
const FormData = require('form-data');
const form = new FormData();
form.append('my_field', 'my value');
form.append('my_buffer', new Buffer(10));
form.append('my_file', fs.createReadStream('/foo/bar.jpg'));
axios.post('https://example.com', form)
🆕 自动序列化
¥🆕 Automatic serialization
从 v0.27.0
开始,如果请求 Content-Type 标头设置为 multipart/form-data
,axios 支持自动将对象序列化为 FormData 对象。
¥Starting from v0.27.0
, Axios supports automatic object serialization to a FormData
object if the request Content-Type header is set to multipart/form-data
.
以下请求将以 FormData 格式(浏览器和 Node.js)提交数据:
¥The following request will submit the data in a FormData format (Browser & Node.js):
import axios from 'axios';
axios.post('https://httpbin.org/post', {
user: {
name: 'Dmitriy'
},
file: fs.createReadStream('/foo/bar.jpg')
}, {
headers: {
'Content-Type': 'multipart/form-data'
}
}).then(({data})=> console.log(data));
Axios FormData 序列化器支持一些特殊的结尾来执行以下操作:
¥Axios FormData serializer supports some special endings to perform the following operations:
-
{}
- 使用 JSON.stringify 序列化值¥
{}
- serialize the value with JSON.stringify -
[]
- 将类似数组的对象解包为具有相同键的单独字段¥
[]
- unwrap the array-like object as separate fields with the same key
注意:解包/展开操作将默认用于数组和 FileList 对象
¥NOTE: unwrap/expand operation will be used by default on arrays and FileList objects
FormData 序列化器通过 config.formSerializer: object
属性支持额外的选项来处理罕见的情况:
¥FormData serializer supports additional options via config.formSerializer: object
property to handle rare cases:
-
visitor: Function
- 用户定义的访问者函数,将按照自定义规则递归调用以将数据对象序列化为FormData
对象。¥
visitor: Function
- user-defined visitor function that will be called recursively to serialize the data object to aFormData
object by following custom rules. -
dots: boolean = false
- 使用点符号而不是括号来序列化数组和对象;¥
dots: boolean = false
- use dot notation instead of brackets to serialize arrays and objects; -
metaTokens: boolean = true
- 在 FormData 键中添加特殊结尾(例如user{}: '{"name": "John"}'
)。后端主体解析器可能会使用此元信息自动将值解析为 JSON。¥
metaTokens: boolean = true
- add the special ending (e.guser{}: '{"name": "John"}'
) in the FormData key. The back-end body-parser could potentially use this meta-information to automatically parse the value as JSON. -
indexes: null|false|true = false
- 控制如何将索引添加到flat
类数组对象的展开键¥
indexes: null|false|true = false
- controls how indexes will be added to unwrapped keys offlat
array-like objects-
null
- 不要添加括号 (arr: 1
,arr: 2
,arr: 3
)¥
null
- don't add brackets (arr: 1
,arr: 2
,arr: 3
) -
false
(default) - 添加空括号(arr[]: 1
、arr[]: 2
、arr[]: 3
)¥
false
(default) - add empty brackets (arr[]: 1
,arr[]: 2
,arr[]: 3
) -
true
- 添加带有索引的括号(arr[0]: 1
、arr[1]: 2
、arr[2]: 3
)¥
true
- add brackets with indexes (arr[0]: 1
,arr[1]: 2
,arr[2]: 3
)
-
假设我们有这样一个对象:
¥Let's say we have an object like this one:
const obj = {
x: 1,
arr: [1, 2, 3],
arr2: [1, [2], 3],
users: [{name: 'Peter', surname: 'Griffin'}, {name: 'Thomas', surname: 'Anderson'}],
'obj2{}': [{x:1}]
};
以下步骤将由 Axios 序列化器在内部执行:
¥The following steps will be executed by the Axios serializer internally:
const formData= new FormData();
formData.append('x', '1');
formData.append('arr[]', '1');
formData.append('arr[]', '2');
formData.append('arr[]', '3');
formData.append('arr2[0]', '1');
formData.append('arr2[1][0]', '2');
formData.append('arr2[2]', '3');
formData.append('users[0][name]', 'Peter');
formData.append('users[0][surname]', 'Griffin');
formData.append('users[1][name]', 'Thomas');
formData.append('users[1][surname]', 'Anderson');
formData.append('obj2{}', '[{"x":1}]');
import axios from 'axios';
axios.post('https://httpbin.org/post', {
'myObj{}': {x: 1, s: "foo"},
'files[]': document.querySelector('#fileInput').files
}, {
headers: {
'Content-Type': 'multipart/form-data'
}
}).then(({data})=> console.log(data));
axios 支持以下快捷方法:postForm
、putForm
、patchForm
就是对应的 HTTP 方法,content-type 标头预设为 multipart/form-data
。
¥Axios supports the following shortcut methods: postForm
, putForm
, patchForm
which are just the corresponding http methods with the content-type header preset to multipart/form-data
.
FileList
对象可以直接传递:
¥FileList
object can be passed directly:
await axios.postForm('https://httpbin.org/post', document.querySelector('#fileInput').files)
所有文件都将使用相同的字段名称发送:files[]
;
¥All files will be sent with the same field names: files[]
;