Some scenarios, such as images obtained by canvas, or images returned by WeChat development SDK are in data:img format. We need to upload them to the server, and then they need to be converted.
Convert dataURL to Blob
// convert base64 to blobdataURItoBlob(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 });},
Build Form upload form
const blob = dataURItoBlob(imgDataUrl); const formData = new FormData();// formData.append('auth', state.token.auth); You can optionally add some authentication formData.append('file', blob ); To upload data, I use axiosconst params = { url: '/store/file', payload: formData }; const data = await this.upload(params);
I have encapsulated axios
export const upload = (params) => { const { url, payload } = params return axios.post(url, payload, { headers: { 'Content-Type': 'multipart/form-data' } }).then( x => x.data)}
The above is the entire content of this article. I hope it will be helpful to everyone’s study. I also hope everyone will support VeVb Wulin Network.