Firebase存储上载的动态进度条

时间:2017-04-17 10:01:53

标签: angular firebase firebase-storage

我的问题是我无法直接从firebase.storage.UploadTaskSnapshot.bytesTransferred获取firebasePutString,但需要使用.on("state_changed")方法,但此方法仅每隔几秒钟调用一次(每256Kb) ,所以进度条不是真正的动态。我无法弄清楚如何直接从我的firebasePutString对象中调用它。任何想法??

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() {});

2 个答案:

答案 0 :(得分:1)

Firebase Storage SDK仅以256KB为增量报告进度。除非你想出一些自己衡量进步的低级方法,否则这就好了。

答案 1 :(得分:1)

这是我解决方案的代码,不是最优雅的代码,但效果相当不错:

让interim:number = 0;     let firebaseRef = firebase.storage()。ref(/path/);     让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);
    }
  });