Javascript 检测AngularJS中异步文件上载的进度
我试图在服务器打开后上传我的文件。我的服务中有一个函数,可以调用该服务来上传我的文件。这是我的服务功能Javascript 检测AngularJS中异步文件上载的进度,javascript,html,angularjs,Javascript,Html,Angularjs,我试图在服务器打开后上传我的文件。我的服务中有一个函数,可以调用该服务来上传我的文件。这是我的服务功能 function post(file) { var file = file; if (angular.isDefined(file)) { return Upload.upload({ url: filesConfig.uploadFile, data: { file: file } }).then(function (response) {
function post(file) {
var file = file;
if (angular.isDefined(file)) {
return Upload.upload({
url: filesConfig.uploadFile,
data: {
file: file
}
}).then(function (response) {
return response;
},
function (error) {
return error;
},
function (evt) {
var progress = parseInt(100.0 * evt.loaded / evt.total);
console.log('progress: ' + progress + '% ' + evt.config.data.file.name);
});
}
}
在最后一个evt arg函数中,我在变量方面取得了进展。我是这样从控制器调用这个post函数的
angular.element(document.querySelector('#fileinput')).on('change', function () {
for (var i = 0; i < this.files.length; i++) {
vm.filess.push(this.files[i]);
fileUpload.post(vm.filess[i]).then(function (response) {
console.log(response);
});
}
});
现在我想检测控制器中每个文件的进度,以便在UI中显示进度条。如何检测进度?下面是最快、最肮脏的解决方案 在控制器中: 这样做,您将文件包装在一个item对象中,并将文件作为该对象的属性。在您的服务中,您直接修改项目的引用 在视图中,您只需要遍历vm.files,就可以访问动态添加的属性progress
不是最好的解决方案,我认为这是我能想到的最快的设置方法。1-使用一个回调,作为参数发送到postfile,回调,然后在每次进度更改时执行回调;或2-使用发布/订阅在每次进度更改时发送事件,然后在控制器中订阅此事件;或3-使用一个中介/管理器/服务对象,该对象保持对该进度的引用,并在每个步骤上更新它,然后将该引用注入控制器并使用它;或者4-使用进度值更新文件的参考,例如file.progress=服务内部的进度-不太直观-您能用代码示例详细说明吗?
angular.element(document.querySelector('#fileinput')).on('change', function() {
for (var i = 0; i < this.files.length; i++) {
var item = {
file: this.files[i]
};
vm.filess.push(item);
fileUpload.post(item).then(function (response) {
console.log(response);
});
}
});
function post(item) {
var file = item.file;
if (angular.isDefined(file)) {
return Upload.upload({
url: filesConfig.uploadFile,
data: {
file: file
}
}).then(function (response) {
return response;
},
function (error) {
return error;
},
function (evt) {
item.progress = parseInt(100.0 * evt.loaded / evt.total);
});
}
}