一些場景,好比canvas獲取的圖片,或者微信開發sdk返回的圖片格式是data:img格式的,咱們須要上傳到服務器上,那就須要進行轉化。
// 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 }); },
const blob = dataURItoBlob(imgDataUrl); const formData = new FormData(); // formData.append('auth', state.token.auth); 能夠選擇性的加入一些鑑權 formData.append('file', blob);
const params = { url: '/store/file', payload: formData }; const data = await this.upload(params);
export const upload = (params) => { const { url, payload } = params return axios.post(url, payload, { headers: { 'Content-Type': 'multipart/form-data' } }).then(x => x.data) }