user2419560 user2419560 - 3 months ago 27
HTTP Question

how do I get this promise back to the controller?

So I have a series of functions I've defined in the service that upload an image to my Amazon s3 bucket, and I can console.log and alert in the service itself and everything is coming back correct.

However, now I want to return that promise to the controller so I can let the user know the upload is finished. I'm just not sure how I would do that. I've tried putting returns at the filereader.onload but then I get errors saying that what I've given back isn't a promise and such. Here's my code:

angular.module("testApp", [])
.controller("testCtrl", function($scope, amazonService) {
$scope.test = "leeroy jenkins";

$scope.upload = function() {
amazonService.uploadImage($('#file'));
}
})
.service("amazonService", function($http) {
var url = "/api/"
var uploadImageFilestream = function(obj) {
return $http({
method: "PUT",
url: url + "media/images",
data: obj
}).then(function(res) {
if (res.status === 200) {
alert("upload successful!");
}
return res;
});
}

var formatFileName = function(filename, newBase) {
//first, get the file extension
var extension = filename.substring(filename.lastIndexOf("."));
return newBase + extension;
}

this.uploadImage = function(obj) {
var file = obj[0].files[0];
var fileReader = new FileReader();

fileReader.onload = function(loaded) {
uploadImageFilestream({fileName: formatFileName(file.name, "test1"), fileBody: loaded.target.result});
}

fileReader.readAsDataURL(file);
}
})


I know that if I combined the uploadImageFilestream function with the uploadImage function it would work, but I'm not sure how to structure it with the promise in a separate function.

Answer

Use $q:

.service("amazonService", function($http, $q) {
    var url = "/api/"
    var uploadImageFilestream = function(obj) {
        return $http({
            method: "PUT",
            url: url + "media/images",
            data: obj
        });
    }

    var formatFileName = function(filename, newBase) {
        //first, get the file extension
        var extension = filename.substring(filename.lastIndexOf("."));
        return newBase + extension;
    }

    this.uploadImage = function(obj) {
        var file = obj[0].files[0];
        var fileReader = new FileReader();

        var deferer = $q.defer();

        fileReader.onload = function(loaded) {
            uploadImageFilestream({fileName: formatFileName(file.name, "test1"), fileBody: loaded.target.result})
            .then(function(res) {
                if (res.status === 200) {
                    deferer.resolve();
                    alert("upload successful!");
                }
                return res;
            });
        }

        fileReader.readAsDataURL(file);

        return deferer.promise;
    }
})
Comments