Currently, I am facing an issue with converting a JS File object into a base64 value and returning that value within a JSON object. My approach involves using FileReader.readAsDataURL(), however, due to the asynchronous nature of this process, it appears that I am not obtaining the base64 value 'on time'. This results in the obj.data value being undefined when I call the callback function.
function mapFileData(file, callback) {
var obj = {};
obj.name = file.filename;
obj.size = file.fileSize;
obj.type = file.fileType;
obj.data = getBase64(file);
});
console.log(JSON.stringify(obj)); // file object with undefined 'data' value
callback(obj);
}
function getBase64(file) {
var fileReader = new FileReader();
if (file) {
fileReader.readAsDataURL(file);
}
fileReader.onload = function(event) {
return event.target.result;
};
}
I am unsure how to resolve the issue of making the obj.data
value available when I invoke callback(obj)
. Any suggestions or guidance would be greatly appreciated!