Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS promise not resolving file with FileReader [duplicate]

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);
                 });
};
like image 800
Corey Michael Cochran Avatar asked Apr 16 '26 20:04

Corey Michael Cochran


1 Answers

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;
};
like image 163
Ben Fortune Avatar answered Apr 18 '26 09:04

Ben Fortune



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!