我目前正在上传一个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提供程序重构此代码段吗?我不知道如何留住我的事件监听器。
发布于 2013-04-16 05:35:13
Short answer:很快您就可以这样做了,但还不完全符合您的要求。
有几个选项正在讨论中,以构建功能-公开基本xhr对象,或允许为方法设置回调。
请具体查看https://github.com/angular/angular.js/issues/1934 -进度事件暂时不起作用。
同时,我建议您手动创建一个对象,并使用$apply更新您的作用域,就像您所做的那样。
有关如何使用服务设置至少可以捕获的启动和停止事件的更多详细信息,请参阅此问题-但没有进展。
AngularJS: need to fire event every time an ajax call is started
发布于 2013-10-29 06:42:59
现在你可以使用angular-file-upload指令,它很简单/轻量级,支持文件丢弃和上传过程。它使用填充程序在angular之前加载,以便能够访问angular中的XHR私有对象,并将upload事件侦听器附加到该对象。
<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);
});
}
}
}];https://stackoverflow.com/questions/16023548
复制相似问题