我有一系列需要上传到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 返回azure存储路径,我需要将路径推送到imagePathsArray
我如何使用Angular Promise等待上传完成的所有文件,所有路径都存储在imagePathsArray中,以便我可以继续
$scope.data.Images = imagePathsArray ;
这样我就可以获取数组中的路径并执行$ http post?
答案 0 :(得分:3)
您可以使用use OpenTransaction() to create the transaction执行此操作。
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);
})
};
答案 1 :(得分:0)
在上传功能的成功回调中,推送路径后:
imagePathsArray.push(resp.data);
if(imagePathsArray.length == $scope.filesimage.length){
pushtoDatabase();
}
在pushtoDatabase
内调用$http({ .... });
注意:您可能想要考虑上传失败的可能性。在这种情况下,你可以使用失败文件的计数器说failCounter
,然后在if检查条件
if ((imagePathsArray.length + failCounter) == $scope.filesimage.length){....}