項(xiàng)目有上傳圖片需求,查找一番發(fā)現(xiàn)第三方的很麻煩,還要適配手機(jī)系統(tǒng).在此記錄一下如何使用fetch上傳.
uploadImage(imgUrl) {
let url = Url.ossFile; //圖片服務(wù)器
let formData =new FormData();// 把圖片放入formData中,采用formData來(lái)實(shí)現(xiàn)
let file = { uri: imgUrl, type: 'multipart/form-data', name: 'image.png' };// 這里的key(uri和type和name)不能改變,此處type也有可能是'application/octet-stream',看后臺(tái)配置
formData.append('file', file); // 有可能是file 也有可能是images 看后臺(tái)的配置
return fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data; charset = utf-8'
},
body: formData
})
.then((response) => response.text())
.then((responseData) => {
console.log('responseData', responseData);
})
.catch((error) => {console.error('error', error) });
}
這樣即可上傳完成.