function dataURLtoBlob(dataUrl: string) {
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 Blob([u8arr], {
type: mime,
});
}
export function downloadBase64(data: string, options: { fileName?: string } = {}) {
const blobImage = dataURLtoBlob(data);
const fileOfBlob = new File([blobImage], `${options.fileName || new Date()}.jpg`);
const aDom = document.createElement('a');
aDom.download = fileOfBlob.name;
let href = URL.createObjectURL(fileOfBlob);
aDom.href = href;
document.body.appendChild(aDom);
aDom.click(); // 触发 a 标签的点击
document.body.removeChild(aDom);
URL.revokeObjectURL(href);
}
总结:在utils文件夹中创建downloadBase64.ts文件即可