记录工具方法 base64toFile
base64 转 File 文件
如果未传入文件名,通过base64截取生成文件名
使用限制:浏览器
说明:使用了Web API window.atob
/**
* base64 转 file文件
* @param {string} base64
* @param {string} fileName 带扩展名的文件名
* @returns <File>
*/
export function base64toFile(base64, fileName) {
// base64 = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...';
const regex = /^data:(.+\/(.+));base64,(.*)$/;
const matches = base64.match(regex);
if (!matches) {
return;
}
const [, mimeType, fileType, fileData] = matches;
const bstr = window.atob(fileData);
let n = bstr.length;
const u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
if (!fileName) {
const name = base64.match(/[^/]*$/);
fileName = `${name}.${fileType}`;
}
return new File([u8arr], fileName, { type: mimeType });
}