File文件流与base64图片格式转换
使用场景:将上传的图片缓存到本地(文件流无法缓存到本地存储中)
// base64转文件 export function base64ToFile(base64: any, fileName: string) { if(!base64) return let data = base64.split(','); let type = data[0].match(/:(.*?);/)[1]; const bstr = window.atob(data[1]); let n = bstr.length; const u8arr = new Uint8Array(n); while (n--) { u8arr[n] = bstr.charCodeAt(n); } const file = new File([u8arr], `${fileName}`, { type: type, }); return file; } /** 文件转base64 */ export function fileToBase64(file: File) { return new Promise((resolve, reject) => { try { var reader = new FileReader(); reader.onloadend = function() { resolve(reader.result); }; reader.readAsDataURL(file); } catch { reject(); } }); }