我试图显示多个文件上传的进度条,但如果服务器因任何原因拒绝它,我希望它重置为0
当使用angular-file-upload
选择输入时触发以下代码:
$scope.start = function(index) {
$scope.errors = null;
$scope.progress[index] = 0;
$scope.upload[index] = $upload.upload({
url: API_URL.url + API_URL.loc + 'shop/upload/file',
method: 'POST',
headers: {},
useXDomain: true,
data: {entry_id: 1, resource_type: 'file', resource_content_type: 'image', resource: $scope.selectedFiles[index], auth_token: UserService.token},
}).then(function(response) {
$scope.errors = null;
$scope.uploadResult.push(response.data.result);
}, function(failure) {
$scope.errors = failure.data;
}, function(evt) {
if(angular.isUndefined($scope.errors) || $scope.errors === null) {
$scope.progress[index] = parseInt(100.0 * evt.loaded / evt.total);
} else {
$scope.progress[index] = 0;
}
});
}
然而,当我在error
中设置$scope.errors = failure;
时,为时已晚,因为它总是先进入function(evt)
。所以最后所有的进度都显示为0%
我的理解是文件必须在服务器拒绝它之前发送到服务器,这就是为什么$scope.errors
设置得太晚了。
我试着改变一下,用.then
, .error
, .progress
代替,但无济于事。
我能做些什么来解决这个问题?
您提到要上传多个文件,但是您正在设置$scope。每个上传项目都有单独的错误。
除非您为每个文件分别更新用户的上传状态,否则您可能需要考虑使用errors[index] (见下文)之类的内容,以便跟踪所有文件错误。
此外,因为您总是在获得failure
之前获得evt
,所以您可以在所有这些完成后对$scope.progress[index]
进行检查/设置。你的进度条会上升到100,但它会回到0。
还注意我们在第2行创建$scope.errors
数组,因此稍后设置$scope.errors[index]
不会导致错误。
作为旁注:
} else {
$scope.errors[index] = null;
}
我认为现在不再需要else
了,因为每次调用$scope.start
时我们都会设置errors
。
$scope.start = function(index) {
$scope.errors = []; // Create errors array so we can set each index later on
$scope.progress[index] = 0;
$scope.upload[index] = $upload.upload({
url: API_URL.url + API_URL.loc + 'shop/upload/file',
method: 'POST',
headers: {},
useXDomain: true,
data: {entry_id: 1, resource_type: 'file', resource_content_type: 'image', resource: $scope.selectedFiles[index], auth_token: UserService.token},
}).then(function(response) {
$scope.uploadResult.push(response.data.result);
}, function(failure) {
$scope.errors[index] = failure.data;
}, function(evt) {
$scope.progress[index] = parseInt(100.0 * evt.loaded / evt.total);
}).then(function(){ // After everything else is done
if(!(angular.isUndefined($scope.errors[index]) || $scope.errors[index] === null))
$scope.progress[index] = 0; // Set progress back to 0 if there's an error
});
}