Reputation: 1673
I am trying to upload my file(s) on server once opened. I have a function in my service and calling that service to upload my file(s). This is my service function.
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);
});
}
}
In last evt arg function I am getting progress in variable. I am calling this post function from controller like this.
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);
});
}
});
Now I want to detect progress of each file in my controller, to show progress bar in UI. How to detect progress?
Upvotes: 0
Views: 118
Reputation: 2555
Quickest and somehow dirtiest solution is below.
In controller:
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);
});
}
});
In service:
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);
});
}
}
Doing that, you're wrapping your file
within an item object, keeping file
as property on that object. In your service, you're directly modifying the reference for your item.
On view, you just need to loop through vm.filess
and you can access the dynamically property progress
added.
Is not the best solution, I think that's the quickest I can think of with your setup.
Upvotes: 1