js异步请求fetch
Fetch上传文件(不需要设置headers)
实例代码:其它参数可不加把文件放在body中就行
// 上传文件
function uploadFile(f, name) {
const fd = new FormData()
fd.append('file', f, name)
fetch('/jeecg-boot/leading/upload', {
method: 'POST',
body: fd,
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, same-origin, *omit
mode: 'cors', // no-cors, cors, *same-origin
redirect: 'follow', // manual, *follow, error
referrer: 'no-referrer', // *client, no-referrer
headers: {
'user-agent': 'Mozilla/4.0 MDN Example',
// 'Content-Type': 'multipart/form-data',
'token': sessionStorage['token']
}
}).then(res => res.json()).then(res => {
if (res.success) {
}
})
}
注意 上传文件的时候不要设置headers 的Content-Type属性,不然后台接受不到值!
boundary的重要性
在rfc1867协议中规定,我们在指定content-type为multipart/form-data时,表明我们需要传递的是多媒体内容,我们需要指定boundary【分隔符】来分割当上传多个文件/图片。boundary是随机生成的数字和字母的组合。按照上面的写法可以看出,Request Header里面的content-type中只是设置了multipart/form-data,而没有随机生成的boundary值,也就是把header去掉,不指定Content-Type;Request Header中的Content-Type就默认设置为了multipart/form-data;