How do I extract the Base64 string from a FileReader (NextJs typescript)?

37 views Asked by At

I am receiving an object from the response, and I want to extract the string.

const convertFileToBase64 = (file: File): Promise<string> => {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file); // Read as Data URL (includes Base64 encoding)
        reader.onload = () => {
            const base64 = (reader.result as string).split(',')[1];
            resolve(base64);
        };
        reader.onerror = error => reject(error);
    });
};

log details

I tried using split but it is still returning the object:

reader.onload = () => {
    const base64 = (reader.result as string).split(',')[1];
    resolve(base64);
};
1

There are 1 answers

0
B.tebalo On

I managed to extract the string, here is my implementation

if (values.institution_recommendations.attachment) {
    const reader = new FileReader();
    reader.onload = () => {
        values.institution_recommendations.attachment = (reader.result as string).split(',')[1];
    };
    reader.readAsDataURL(values.institution_recommendations.attachment);     
}