我正在用angular指令上传一个文件…
var fd = new FormData();
fd.append("uploadedFile", scope.uploadedFile);
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", uploadProgress, false);
xhr.addEventListenter("load", uploadComplete, false);
xhr.addEventListenter("error", uploadFailed, false);
xhr.addEventListenter("abort", uploadCanceled, false);
xhr.open("POST", scope.postUrl);
scope.uploadInProgress = true;
xhr.send(fd);
function uploadProgress(e){
scope.$apply(function(){
if(e.lengthComputable){
scope.progress = Math.round(e.loaded * 100 / e.total);
} else {
scope.progress = 'unable to compute';
}
});
}
...
这个片段可以用$http provider重构吗?我不知道如何保留我的事件侦听器。
简短的回答:很快你就可以了,但还没有完全按照你的要求。
讨论了几个选项来构建功能——公开基本的xhr
对象,或者允许为方法设置回调。
具体参见https://github.com/angular/angular.js/issues/1934 -进度事件暂时不起作用。
同时,我建议手动创建一个对象,并使用$apply
来更新您的作用域,就像您所做的那样。
关于如何使用服务设置至少可以捕获的启动和停止事件的更多细节,请参阅这个问题。
AngularJS:需要在每次ajax调用开始时触发事件
现在你可以使用angular-file-upload指令,这是一个简单/轻量级的指令,支持文件拖放和上传进度。它使用了一个加载在angular之前的shim,以便angular能够访问XHR私有对象,并将上传事件监听器附加到它上面。
<div ng-controller="MyCtrl">
<input type="file" ng-file-select="onFileSelect($files)" multiple>
</div>
JS:
//inject angular file upload directive.
angular.module('myApp', ['angularFileUpload']);
var MyCtrl = [ '$scope', '$upload', function($scope, $upload) {
$scope.onFileSelect = function($files) {
for (var i = 0; i < $files.length; i++) {
var $file = $files[i];
$upload.upload({
url: 'my/upload/url',
file: $file,
progress: function(evt){
$scope.progress = parseInt(100.0 * evt.loaded / evt.total);
}
}).then(function(data, status, headers, config) {
// file is uploaded successfully
console.log(data);
});
}
}
}];