Base64转Blob对象
/**
* Base64 转 Blob
* @param {String} dataurl base64内容
* @param {String} mimetype mime标识
* @return {Blob} blob
*/
export function dataURLToBlob(dataurl, mimetype) {
let arr = dataurl.split(','),
mime = mimetype || arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]),
n = bstr.length,
u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], {type:mime});
}
Blob对象转Base64
/**
* Blob 转 Base64
* @param {Blob} blob Blob对象
* @return {Object} promise
*/
export function blobToDataURL(blob) {
return new Promise((resolve, reject) => {
let fileReader = new FileReader();
fileReader.onload = (e) => {
resolve(e.target.result);
}
fileReader.readAsDataURL(blob);
});
}
Base64转File文件对象
/**
* Base64 转 File
* @param {String} dataurl base64内容
* @param {String} filename 文件名
* @return {File} file
*/
export function dataURLtoFile(dataurl, filename) { //将base64转换为文件
let arr = dataurl.split(','),
mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]),
n = bstr.length,
u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new File([u8arr], filename, {type:mime});
}
Blob转临时路径
/**
* Blob 转 Base64
* @param {Blob} blob Blob对象
*/
export function blobToUrl(blob) {
return window.URL.createObjectURL(blob)
}
评论区