angular在1.5.5以上的版本中,在$http中也加入了eventHandler和uploadEventHandlers等方法。
发送请求:
$http({ method:"POST", url:basePath+"/roadShow/saveOrUpdate", eventHandlers: { progress: function(c) { console.log('Progress -> ' + c); console.log(c); } }, uploadEventHandlers: { progress: function(e) { console.log('UploadProgress -> ' + e); console.log(e.loaded/e.total*100); } }, data:form, headers:{"Content-Type":undefined}, transformRequest: angular.identity })
$scope.uploadSample = function(sampleFile){ var fd = new FormData(); fd.append('file',sampleFile); $http({ method:'post', uploadEventHandlers: { progress: function(e) { $scope.sampleFile.progress = parseInt(e.loaded/e.total*100); } }, url:$scope.baseUrl + 'sampleCenter/administration', data:fd }).then(function(response){ if(response.data.error){ ngTip.tip(response.data.error, 'error'); }else{ ngTip.tip(response.data.success, 'success'); } },function(){ ngTip.tip('上传失败请与管理员联系', 'error'); }) }
<div class="login_wrapper"> <form name="fileForm"> <fieldset> <legend>文件上传</legend> <div class="form-group"> <input type="file" ngf-select ng-model="sampleFile" name="filename" accept=".xlsx" required ngf-model-invalid="errorFile"> <i ng-show="fileForm.file.$error.required">*请选择文件</i> </div> <div class="form-group"> <button ng-click="sampleFile = null" ng-show="sampleFile" class="btn btn-danger btn-sm">移除</button> <button ng-disabled="!fileForm.$valid" ng-click="uploadSample(sampleFile)" class="btn btn-primary btn-sm">上传</button> </div> <div class="form-group"> <div class="progress"> <div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="{{sampleFile.progress}}%" ng-bind="sampleFile.progress + '%'"></div> </div> </div> </fieldset> </form> </div>
其中,可以用e.loaded/e.total*100来计算进度:
实际应用时,可结合Math.floor()。