Saturday, July 20, 2019

javascript - AngularJS promise not resolving file with FileReader




I am trying to write a very simple function in my service that will create a FileReader, read the small image file I send it and return this result in a promise to my controller. The file gets to my service just fine. It gets to my controller and logs just a blank line. I assume I am messing up the promise part of this somehow. Where am I going wrong there?



Service funtion --




this.fileRead  = function(file) {
var deferred = $q.defer();

var reader = new FileReader();
reader.readAsDataURL(file);

deferred.resolve(reader.result);

return deferred.promise;

};


Controller function --



$scope.onFileSelect = function($files) {
MyService.fileRead($files[0])
.then(function(result) {
console.log(result);
});

};

Answer



You have no onload event, so it doesn't actually return the read file data.



this.fileRead  = function(file) {
var deferred = $q.defer();

var reader = new FileReader();


reader.onload = function() {
deferred.resolve(reader.result);
};

reader.readAsDataURL(file);

return deferred.promise;
};

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...