feat: download 统一使用@vben/utils
This commit is contained in:
@@ -140,6 +140,63 @@ export function urlToBase64(url: string, mineType?: string): Promise<string> {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 将 Base64 字符串转换为文件对象
|
||||
* @param base64 - Base64 字符串
|
||||
* @param fileName - 文件名
|
||||
* @returns File 对象
|
||||
*/
|
||||
export function base64ToFile(base64: string, fileName: string): File {
|
||||
// 输入验证
|
||||
if (!base64 || typeof base64 !== 'string') {
|
||||
throw new Error('base64 参数必须是非空字符串');
|
||||
}
|
||||
|
||||
// 将 base64 按照逗号进行分割,将前缀与后续内容分隔开
|
||||
const data = base64.split(',');
|
||||
if (data.length !== 2 || !data[0] || !data[1]) {
|
||||
throw new Error('无效的 base64 格式');
|
||||
}
|
||||
|
||||
// 利用正则表达式从前缀中获取类型信息(image/png、image/jpeg、image/webp等)
|
||||
const typeMatch = data[0].match(/:(.*?);/);
|
||||
if (!typeMatch || !typeMatch[1]) {
|
||||
throw new Error('无法解析 base64 类型信息');
|
||||
}
|
||||
const type = typeMatch[1];
|
||||
|
||||
// 从类型信息中获取具体的文件格式后缀(png、jpeg、webp)
|
||||
const typeParts = type.split('/');
|
||||
if (typeParts.length !== 2 || !typeParts[1]) {
|
||||
throw new Error('无效的 MIME 类型格式');
|
||||
}
|
||||
const suffix = typeParts[1];
|
||||
|
||||
try {
|
||||
// 使用 atob() 对 base64 数据进行解码,结果是一个文件数据流以字符串的格式输出
|
||||
const bstr = window.atob(data[1]);
|
||||
|
||||
// 获取解码结果字符串的长度
|
||||
const n = bstr.length;
|
||||
// 根据解码结果字符串的长度创建一个等长的整型数字数组
|
||||
const u8arr = new Uint8Array(n);
|
||||
|
||||
// 优化的 Uint8Array 填充逻辑
|
||||
for (let i = 0; i < n; i++) {
|
||||
// 使用 charCodeAt() 获取字符对应的字节值(Base64 解码后的字符串是字节级别的)
|
||||
// eslint-disable-next-line unicorn/prefer-code-point
|
||||
u8arr[i] = bstr.charCodeAt(i);
|
||||
}
|
||||
|
||||
// 返回 File 文件对象
|
||||
return new File([u8arr], `${fileName}.${suffix}`, { type });
|
||||
} catch (error) {
|
||||
throw new Error(
|
||||
`Base64 解码失败: ${error instanceof Error ? error.message : '未知错误'}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 通用下载触发函数
|
||||
* @param href - 文件下载的 URL
|
||||
|
||||
Reference in New Issue
Block a user