mirror of
https://github.com/CorentinTh/it-tools.git
synced 2025-04-21 07:16:15 -04:00
refactor(base64-to-file): clean validation to convert base64 to file
This commit is contained in:
parent
5f03619ab4
commit
750a76b00f
4 changed files with 113 additions and 22 deletions
|
@ -1,16 +1,35 @@
|
|||
import { extension as getExtensionFromMime } from 'mime-types';
|
||||
import type { Ref } from 'vue';
|
||||
|
||||
function getFileExtensionFromBase64({
|
||||
base64String,
|
||||
defaultExtension = 'txt',
|
||||
}: {
|
||||
base64String: string;
|
||||
defaultExtension?: string;
|
||||
}) {
|
||||
const hasMimeType = base64String.match(/data:(.*?);base64/i);
|
||||
|
||||
if (hasMimeType) {
|
||||
return getExtensionFromMime(hasMimeType[1]) || defaultExtension;
|
||||
}
|
||||
|
||||
return defaultExtension;
|
||||
}
|
||||
|
||||
export function useDownloadFileFromBase64({ source, filename }: { source: Ref<string>; filename?: string }) {
|
||||
return {
|
||||
download() {
|
||||
const base64 = source.value;
|
||||
const mimeType = base64.match(/data:(.*?);base64/i)?.[1] ?? 'text/plain';
|
||||
console.log({ mimeType });
|
||||
const cleanFileName = filename ?? `file.${getExtensionFromMime(mimeType)}`;
|
||||
const base64String = source.value;
|
||||
|
||||
if (base64String === '') {
|
||||
throw new Error('Base64 string is empty');
|
||||
}
|
||||
|
||||
const cleanFileName = filename ?? `file.${getFileExtensionFromBase64({ base64String })}`;
|
||||
|
||||
const a = document.createElement('a');
|
||||
a.href = source.value;
|
||||
a.href = base64String;
|
||||
a.download = cleanFileName;
|
||||
a.click();
|
||||
},
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue