项目在涉及文件上传业务时,通常解决方案是将文件、其他参数放到FormData实例对象中,最后将FormDat实例对象传给后端,后端解析获取文件和参数。此时,请求头中的Content-Type参数值变为multipart/form-data。FormData-API
- FormData:append & set
set:给
FormData设置属性值,如果FormData对应的属性值存在则覆盖原值,否则新增一项属性值。
append:向
FormData中添加新的属性值,FormData对应的属性值存在也不会覆盖原值,而是新增一个值,如果属性不存在则新增一项属性值。
- 单文件上传
const formData = new FormData()
formData.append('file', file)
formData.append('name', 'LRT')
- 多文件上传
const formData = new FormData()
formData.append('files', file1)
formData.append('files', file2)
formData.append('name', 'LRT')
- 传数组和对象
// 传数组和对象有其他方案,我一般会使用序列化方式,后端拿到后,反序列化。比较简便
formData.append('file', file)
formData.append('array', JSON.stringify(['1', '2', '3']))
formData.append('object', JSON.stringify({
name: 'LRT',
age: 26
}))