2022-07-25 23:21:42 +02:00
|
|
|
import { extension as getExtensionFromMime } from 'mime-types';
|
2022-04-14 18:18:15 +02:00
|
|
|
import type { Ref } from 'vue';
|
2023-11-13 11:44:23 +01:00
|
|
|
import _ from 'lodash';
|
2022-04-14 18:18:15 +02:00
|
|
|
|
2023-11-13 11:44:23 +01:00
|
|
|
export { getMimeTypeFromBase64, useDownloadFileFromBase64 };
|
|
|
|
|
|
|
|
const commonMimeTypesSignatures = {
|
|
|
|
'JVBERi0': 'application/pdf',
|
|
|
|
'R0lGODdh': 'image/gif',
|
|
|
|
'R0lGODlh': 'image/gif',
|
|
|
|
'iVBORw0KGgo': 'image/png',
|
|
|
|
'/9j/': 'image/jpg',
|
|
|
|
};
|
|
|
|
|
|
|
|
function getMimeTypeFromBase64({ base64String }: { base64String: string }) {
|
|
|
|
const [,mimeTypeFromBase64] = base64String.match(/data:(.*?);base64/i) ?? [];
|
|
|
|
|
|
|
|
if (mimeTypeFromBase64) {
|
|
|
|
return { mimeType: mimeTypeFromBase64 };
|
|
|
|
}
|
|
|
|
|
|
|
|
const inferredMimeType = _.find(commonMimeTypesSignatures, (_mimeType, signature) => base64String.startsWith(signature));
|
|
|
|
|
|
|
|
if (inferredMimeType) {
|
|
|
|
return { mimeType: inferredMimeType };
|
|
|
|
}
|
|
|
|
|
|
|
|
return { mimeType: undefined };
|
|
|
|
}
|
|
|
|
|
|
|
|
function getFileExtensionFromMimeType({
|
|
|
|
mimeType,
|
2022-07-29 10:56:04 +02:00
|
|
|
defaultExtension = 'txt',
|
|
|
|
}: {
|
2023-11-13 11:44:23 +01:00
|
|
|
mimeType: string | undefined
|
2023-05-28 23:13:24 +02:00
|
|
|
defaultExtension?: string
|
2022-07-29 10:56:04 +02:00
|
|
|
}) {
|
2023-11-13 11:44:23 +01:00
|
|
|
if (mimeType) {
|
|
|
|
return getExtensionFromMime(mimeType) ?? defaultExtension;
|
2022-07-29 10:56:04 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
return defaultExtension;
|
|
|
|
}
|
|
|
|
|
2023-11-13 11:44:23 +01:00
|
|
|
function useDownloadFileFromBase64({ source, filename }: { source: Ref<string>; filename?: string }) {
|
2022-04-14 18:18:15 +02:00
|
|
|
return {
|
|
|
|
download() {
|
2023-11-13 11:44:23 +01:00
|
|
|
if (source.value === '') {
|
2022-07-29 10:56:04 +02:00
|
|
|
throw new Error('Base64 string is empty');
|
|
|
|
}
|
|
|
|
|
2023-11-13 11:44:23 +01:00
|
|
|
const { mimeType } = getMimeTypeFromBase64({ base64String: source.value });
|
|
|
|
const base64String = mimeType
|
|
|
|
? source.value
|
|
|
|
: `data:text/plain;base64,${source.value}`;
|
|
|
|
|
|
|
|
const cleanFileName = filename ?? `file.${getFileExtensionFromMimeType({ mimeType })}`;
|
2022-07-25 23:21:42 +02:00
|
|
|
|
2022-04-14 18:18:15 +02:00
|
|
|
const a = document.createElement('a');
|
2022-07-29 10:56:04 +02:00
|
|
|
a.href = base64String;
|
2022-07-25 23:21:42 +02:00
|
|
|
a.download = cleanFileName;
|
2022-04-14 18:18:15 +02:00
|
|
|
a.click();
|
|
|
|
},
|
|
|
|
};
|
|
|
|
}
|