I am currently in the process of developing a service that reads image files from an HTML input element. The goal of this service is to return the HTML img object with the updated attribute containing the base64 string of the read image file. Below is the code snippet of my service:
.service('ReadLocalImageService', [function () {
this.openLocalImage = function (file) {
var img = document.createElement("img");
var fileReader = new FileReader();
fileReader.onload = function (e) {
img.src = e.target.result;
};
fileReader.readAsDataURL(file);
return img.src;
};
}]);
Unfortunately, when I retrieve the value of img.src
, it comes back empty, as shown here: https://i.sstatic.net/dG1Vo.png
Upon further investigation, I noticed that a console.log(img.src)
placed inside the fileReader.onload
function does return the expected result. It appears that the openLocalImage
function is returning img.src
before the e.target.result
is properly assigned to it.
I have been struggling to find a solution and have not been able to locate relevant resources on this issue. Can someone provide assistance in resolving this issue or explain why it is occurring?