I'm writing a program in javascript that requires me to get the source data of an image, convert it to base64, and then output it as a relevant html tag. The problem is, the function works when I attempt to log it in console, but it refuses to work when I return it instead.
Any idea on what's going on?
Not Working
undefined
function imageUploaded()
{
var file = document.querySelector('input[type=file]')['files'][0];
var reader = new FileReader();
reader.onload = function ()
{
base64String = reader.result.replace("data:", "").replace(/^.+,/, "");
imageBase64Stringsep = base64String;
return base64String;
}
reader.readAsDataURL(file);
}
Working
base64 encoded string
function imageUploaded()
{
var file = document.querySelector('input[type=file]')['files'][0];
var reader = new FileReader();
reader.onload = function ()
{
base64String = reader.result.replace("data:", "").replace(/^.+,/, "");
imageBase64Stringsep = base64String;
console.log(base64String);
}
reader.readAsDataURL(file);
}
Thanks in advance for the help!
Update
I've solved one problem but stumbled onto another!
Returning the reader object and logging it into the console shows that the object contains the relevant values under 'result', however whenever I try to log the result itself by doing console.log(myVar.result)
, I'm getting null
as an output. This doesn't seem right to me, because the object has the data when you log it normally! What's happening?
console.log(myVar)