问题
My problem is that I can't get firebase.storage.UploadTaskSnapshot.bytesTransferred
directly from firebasePutString
, but need to use the .on("state_changed")
method, but this method is called only every few seconds (every 256Kb), so the progress bar isn't really dynamic. I can't figure out how to call it directly from my firebasePutString
object. Any ideas??
let firebasePutString = firebase.storage().ref(`/${UID}/${fileName}`).putString(data, 'data_url');
firebasePutString.on('state_changed',
function progress(snapshot) {
console.log("snapshot: " + snapshot);
this.percentage = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
console.log("percentage2: " + this.percentage);
},
function error(err) {},
function complete() {});
回答1:
Here's the code of my solution, not the most elegant, but works fairly well:
let interim: number = 0;
let firebaseRef = firebase.storage().ref(/path/
);
let firebasePutString = firebaseRef.putString(data, 'data_url');
let mySubscription = Observable.interval(50).subscribe( _ => {
if (firebasePutString.snapshot.totalBytes === firebasePutString.snapshot.bytesTransferred) {
interim = firebasePutString.snapshot.bytesTransferred;
this.percentage = parseInt(((interim / firebasePutString.snapshot.totalBytes) * 100).toFixed(0));
mySubscription.unsubscribe();
}
else if (interim === 0 && firebasePutString.snapshot.bytesTransferred === 0 && this.percentage < 100) {
this.percentage = this.percentage + 1;
}
else if (interim === 0 && firebasePutString.snapshot.bytesTransferred !== 0) {
interim = firebasePutString.snapshot.bytesTransferred;
(this.percentage < parseInt(((interim / firebasePutString.snapshot.totalBytes) * 100).toFixed(0))) ? this.percentage = parseInt(((interim / firebasePutString.snapshot.totalBytes) * 100).toFixed(0)) : (this.percentage = this.percentage);
}
else if(interim === firebasePutString.snapshot.bytesTransferred && this.percentage < 100) {
this.percentage = this.percentage + 1;
}
else {
interim = firebasePutString.snapshot.bytesTransferred;
(this.percentage < parseInt(((interim / firebasePutString.snapshot.totalBytes) * 100).toFixed(0))) ? this.percentage = parseInt(((interim / firebasePutString.snapshot.totalBytes) * 100).toFixed(0)) : (this.percentage = this.percentage);
}
});
回答2:
The Firebase Storage SDK only reports progress in 256KB increments. Unless you come up with some low-level way of measuring progress on your own, this is as good as it's going to get.
来源:https://stackoverflow.com/questions/43449281/dynamic-progress-bar-for-firebase-storage-upload