一些场景,比如 canvas 获取的图片,或者微信开发 sdk 返回的图片格式是 data:img 格式的,我们需要上传到服务器上,那就需要进行转化。
- 将 dataURL 转成 Blob
// base64 转 blob
dataURItoBlob(dataURI) {
// convert base64/URLEncoded data component to raw binary data held in a string
let byteString;
if (dataURI.split(',')[0].indexOf('base64') >= 0) {byteString = atob(dataURI.split(',')[1]);
} else byteString = unescape(dataURI.split(',')[1]);
// separate out the mime component
const mimeString = dataURI
.split(',')[0]
.split(':')[1]
.split(';')[0];
// write the bytes of the string to a typed array
const ia = new Uint8Array(byteString.length);
for (let i = 0; i < byteString.length; i++) {ia[i] = byteString.charCodeAt(i);
}
return new Blob([ia], {type: mimeString});
},
- 构建 Form 上传表单
const blob = dataURItoBlob(imgDataUrl);
const formData = new FormData();
// formData.append('auth', state.token.auth); 可以选择性的加入一些鉴权
formData.append('file', blob);
- 进行数据上传,我这里使用的是 axios
const params = {
url: '/store/file',
payload: formData
};
const data = await this.upload(params);
- 我已经对 axios 进行了封装
export const upload = (params) => {const { url, payload} = params
return axios.post(url, payload, {
headers: {'Content-Type': 'multipart/form-data'}
}).then(x => x.data)
}