【问题标题】:How to retrieve download Url using getDownloadUrl() after uploading to AngularFireStorage上传到 AngularFireStorage 后如何使用 getDownloadUrl() 检索下载 URL
【发布时间】:2020-11-15 15:25:11
【问题描述】:

我已经成功地将图像上传到我的 firebase 存储中,但我还想检索 downloadURL 并将其添加到我的 firestore 数据库中。控制台日志记录“url”返回我想要的链接。但是我在使用它时遇到了问题。

我已经尝试过this.profileImage = url,但控制台总是会返回错误无法设置未定义的属性“profileImage”。 我通过在构造函数上方执行profileImage 来定义它。

我也尝试过将整个 firestore 函数放入其中,但控制台将返回无法读取未定义的属性 'firestore' 我正在使用 Ionic 5。

imageRef.getDownloadURL().then((url)=> {
    this.firestore.collection('users').doc(this.user.id).update({image.url})
       console.log("this is my image" + url)
})

这是我目前拥有的

uploadImage(imageURI) {
    return new Promise<any>((resolve, reject) => {
      let storageRef = firebase.storage().ref();
      const imageRef = storageRef.child('image').child(this.createFileName());
      this.encodeImageUri(imageURI, function (image64) {
        imageRef.putString(image64, 'data_url')
          .then(function (snapshot) {
            console.log(snapshot)
            resolve(snapshot.downloadURL)
            imageRef.getDownloadURL().then((url)=> {
              this.profileImage = url
              console.log(this.profileImage)
              console.log("this is my image" + url)
            })
          }, err => {
            reject(err);
          })
      })
    })
  }
encodeImageUri(imageUri, callback) {
    var c = document.createElement('canvas');
    var ctx = c.getContext("2d");
    var img = new Image();
    img.onload = function () {
      var aux: any = this;
      c.width = aux.width;
      c.height = aux.height;
      ctx.drawImage(img, 0, 0);
      var dataURL = c.toDataURL("image/jpeg");
      callback(dataURL);
    };
    img.src = imageUri;
  };

【问题讨论】:

  • 检查你的 profileImage 看看它是否是一个字符串

标签: angular firebase google-cloud-firestore firebase-storage ionic5


【解决方案1】:

您的第一个 sn-p 看起来非常接近,但您没有保存从 getDownloadUrl() 获得的实际 url。如果你这样做并将其合并到你的 putString() 回调中,你会得到这样的结果:

imageRef.putString(image64, 'data_url')
  .then((snapshot) => {
    imageRef.getDownloadURL().then((url)=> {
        this.firestore.collection('users').doc(this.user.id).update({ "imageUrl": url })
    })
  })

【讨论】:

  • 我之前尝试过,但控制台将返回无法读取未定义的属性 'firestore'
  • 好的。我更新了对所有回调使用粗箭头表示法的答案,这应该可以解决这个问题。
猜你喜欢
  • 2019-04-28
  • 2018-10-13
  • 2018-11-07
  • 2020-12-21
  • 2020-07-09
  • 2023-03-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多