I'm currently working on saving a JavaScript object that includes binary data along with other values. I want the output to resemble the following:
{
"value":"xyz",
"file1":"[FileContent]",
"file2":"[LargeFileContent]"
}
Previously, I only dealt with JSON data without any binary content. However, as I started incorporating binary data, I encountered issues when handling large files (>1GB).
I attempted the following method: JSON.stringify or how to serialize binary data as base64 encoded JSON? This solution worked for smaller files (around 20MB). But when dealing with larger files, the result from the FileReader always turns out to be an empty string. The resulting output would appear like this:
{
"value":"xyz:,
"file1":"[FileContent]",
"file2":""
}
The code responsible for reading the blobs closely resembles the one mentioned in another post:
const readFiles = async (measurements: FormData) => {
setFiles([]); //This is where the result is stored
let promises: Array<Promise<string>> = [];
measurements.forEach((value) => {
let dataBlob = value as Blob;
console.log(dataBlob); //No issue here
promises.push(
new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(dataBlob);
reader.onloadend = function () {
resolve(reader.result as string);
};
reader.onerror = function (error) {
reject(error);
};
})
);
});
let result = await Promise.all(promises);
console.log(result); //Empty for large file
setFiles(result);
};
Are there any other methods I can attempt?