new-personal-site/components/lib/utils/form/fileInputToBase64.ts
Benjamin Toby 8762e2da8d Updates
2025-03-27 07:37:16 +01:00

60 lines
1.7 KiB
TypeScript

export type FileInputToBase64FunctionReturn = {
fileBase64?: string;
fileBase64Full?: string;
fileName?: string;
fileSize?: number;
fileType?: string;
file?: File;
};
export type FileInputToBase64FunctioParam = {
inputFile: File;
allowedRegex?: RegExp;
};
export default async function fileInputToBase64({
inputFile,
allowedRegex,
}: FileInputToBase64FunctioParam): Promise<FileInputToBase64FunctionReturn> {
const allowedTypesRegex = allowedRegex ? allowedRegex : undefined;
if (allowedTypesRegex && !inputFile?.type?.match(allowedTypesRegex)) {
window.alert(`We currently don't support ${inputFile.type} file type.`);
return { fileName: inputFile.name };
}
let fileName = inputFile.name?.replace(/\..*/, "");
const file = inputFile;
try {
const fileData: string | undefined = await new Promise(
(resolve, reject) => {
var reader = new FileReader();
reader.readAsDataURL(inputFile);
reader.onload = function () {
resolve(reader.result?.toString());
};
reader.onerror = function (/** @type {*} */ error: any) {
console.log("Error: ", error.message);
};
}
);
return {
fileBase64: fileData?.replace(/.*?base64,/, ""),
fileBase64Full: fileData,
fileName: fileName,
fileSize: inputFile.size,
fileType: inputFile.type,
file,
};
} catch (error: any) {
console.log("File Processing Error! =>", error.message);
return {
fileName: inputFile.name,
file,
};
}
}