Jibeee Jibeee - 1 year ago 73
AngularJS Question

Imbrication promises to upload files angularJS

I'm stuck for hours to upload an files array to my server. I need to upload this array and then upload an object using this files array as params. My server sends me back the uploaded file's name on the server side as response. I'm confuse with the promise uses, because I obtain the error :

Cannot read property 'then' of undefined

Here is my code :

function uploadImage(formData){

var deferred = $q.defer();
return deferred.promise;


function uploadImages(gallery){

var myGallery = [];
angular.forEach(gallery, function (image) {
var formData = new FormData();
formData.append('file', image);

var promise = uploadImage(formData);


var mygallery = uploadImages($scope.stock.gallery);

// Then use mygallery ["imgName1.png","imgName2.jpg", ... ]

Answer Source

uploadImage() should return a promise in order to have a then() function. Also, you can simplify your promise returning directly a value.

When you return a value inside then(), this value will be passed to the first chained promise.

function uploadImage(formData) {
    return Image.add(formData).then(function(data) {
        return data.data.fileName;

Then, you should reorganize your uploadImages() function. I suggest the following way.

function uploadImages(gallery) {
    var uploadPromises = gallery.map(function(image) {
        var formData = new FormData();
        formData.append('file', image);
        return uploadImage(formData);

    return Promise.all(uploadPromises);

uploadImages($scope.stock.gallery).then(function(mygallery) {
    // then you should use mygallery

Explanation: You should put all your upload promises into an array. Using Promise.all you can catch the moment when all your uploads are done. Then, you make an array with all filenames available through then().

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download