2

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);
                 });
};
Ben Fortune
  • 31,623
  • 10
  • 79
  • 80

1 Answers1

9

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;
};
Ben Fortune
  • 31,623
  • 10
  • 79
  • 80
  • exactly what I was missing. was now able to create a small image preview piece with this. thanks! – Corey Michael Cochran Sep 12 '14 at 15:37
  • @CoreyMichaelCochran This answer seems to have helped you. You should mark it as helpful by clicking the arrow to the left (it will turn green if you have done this properly). Voting (up/down) helps sort out what community finds to be the best answer, "accepting" an answer tells people which answer helped you the most. Both are good to do! – m59 Sep 22 '14 at 22:21
  • I had already thought I did that. Sorry for the late response. Thanks again. – Corey Michael Cochran Sep 24 '14 at 13:33
  • this is the best solution i found in the web – messerbill Jan 22 '16 at 16:45