2015-11-18 107 views
1

我的照片文件的數組,需要上傳到Azure的雲存儲,並使用foreach循環調用上傳下面我:角鏈的承諾

$scope.savetemplate = function() { 
    var imagePathsArray = []; 

    $scope.filesimage = []; 
    $scope.filesimage.push($scope.file1); 
    $scope.filesimage.push($scope.file2); 
    $scope.filesimage.push($scope.file3); 


    for (var i in $scope.filesimage) { 
     $scope.upload($scope.filesimage[i]); 
    } 


    $scope.data.Images = imagePathsArray ; 

    $http({ 
       //after finish uploads i need to post the paths 
       //of all images to save into database 
    }) 
}; 


$scope.upload = function (file) { 
    Upload.upload({ 
     url: '/uploadImage', 
     data: { file: file } 
    }).then(function (resp) { 
     imagePathsArray.push(resp.data); 

    }) 
}; 

resp.data回報蔚藍存儲路徑,我需要的路徑推入imagePathsArray

我如何使用角無極等待上傳完所有文件和所有的路徑都存儲在imagePathsArray這樣我就可以

進行

這樣我就可以得到數組中的路徑並執行$ http post?

imagePathsArray.push(resp.data); 
if(imagePathsArray.length == $scope.filesimage.length){ 
    pushtoDatabase(); 
} 

pushtoDatabase呼叫$http({ .... });

注意

回答

3

你可以做到這一點與$q.all

var promises = []; 
for (var i in $scope.filesimage) { 
    promises.push(upload($scope.filesimage[i])); 
} 
$q.all(promises).then(function() { 
    $scope.data.Images = imagePathsArray ; 

    $http.post({ 
      //after finish uploads i need to post the paths 
      //of all images to save into database 
    }); 
}); 

function upload(file) { 
    return Upload.upload({ 
     url: '/uploadImage', 
     data: { file: file } 
    }).then(function (resp) { 
     imagePathsArray.push(resp.data); 
    }) 
}; 
+0

Hi Micheal!你的解決方案就像一個魅力!謝謝! – Mentos

0

在上傳功能的成功回調,推路徑後,您不妨考慮一下上傳的概率越來越失敗。在這種情況下,你可以變通使用失敗的文件的櫃檯說failCounter,然後檢查是否對裏面的情況

if ((imagePathsArray.length + failCounter) == $scope.filesimage.length){....}