datasquirel/client/media/inputFileToBase64.ts
2025-01-10 20:10:28 +01:00

69 lines
2.0 KiB
TypeScript

type FunctionReturn = {
fileBase64?: string;
fileBase64Full?: string;
fileName?: string;
fileSize?: number;
fileType?: string;
};
type Param = {
inputFile: File;
allowedRegex?: RegExp;
};
/**
* Input File to base64
* ==============================================================================
*
* @description This function takes in a *SINGLE* input file from a HTML file input element.
* HTML file input elements usually return an array of input objects, so be sure to select the target
* file from the array.
*/
export default async function inputFileToBase64({
inputFile,
allowedRegex,
}: Param): Promise<FunctionReturn> {
const allowedTypesRegex = allowedRegex ? allowedRegex : /image\/*|\/pdf/;
if (!inputFile?.type?.match(allowedTypesRegex)) {
window.alert(
`We currently don't support ${inputFile.type} file types. Support is coming soon. For now we support only images and PDFs.`
);
return {
fileName: inputFile.name,
};
}
try {
let fileName = inputFile.name.replace(/\..*/, "");
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,
};
} catch (error: any) {
console.log("File Processing Error! =>", error.message);
return {
fileName: inputFile.name,
};
}
}