Here's a simple method to locate any file type key in a formdata object and save it in an indexed database.
First, I save the information like this:
const data = item instanceof FormData ? await this.idb.serializeRequestBody(item) : item;
The 'items' variable can be either FormData or JSON(string).
With these functions, I convert my file to base64 to make it readable in an img tag:
public serializeRequestBody(body: FormData): any {
try {
const data: any = {};
body.forEach(async (value, key) => {
if (value instanceof File) {
await this.fileToBase64(value).then((base64) => {
data[key] = base64;
});
} else {
data[key] = value;
}
});
return data;
} catch (error) {
console.error('Error serializing request body:', error);
throw error;
}
}
private async fileToBase64(file: File): Promise<string> {
try {
const reader = new FileReader();
return new Promise<string>((resolve, reject) => {
reader.readAsDataURL(file);
reader.onload = () => {
resolve(reader.result as string);
};
reader.onerror = (error) => {
reject(error);
};
});
} catch (error) {
console.error('Error converting file to Base64:', error);
throw error;
}
}
However, I encountered this issue:
I included it as an image because the URL is too lengthy. I have tried utilizing promises, tryCatch, searched for other solutions, but haven't found one that works for me.
I am hopeful that someone can provide guidance!