【问题标题】:Error when trying to upload blob to Firebase Storage (React Native)尝试将 blob 上传到 Firebase 存储时出错(React Native)
【发布时间】:2020-08-22 15:57:44
【问题描述】:

我的 React-Native 应用程序中有一个图像选择器组件,允许用户选择图像。然后将其保存到 this.state.imageUri。我的目标是将图像上传到 Firebase 存储,然后将其链接到实时数据库,以便可以针对特定列表项对其进行访问。我为此使用了两个函数:

uriToBlob = (uri) => {
    console.log('uri: ' + uri)
    return new Promise(function(resolve, reject) {
      try {
          var xhr = new XMLHttpRequest();
          xhr.open("GET", uri);
          xhr.responseType = "blob";
          xhr.onerror = function() {reject("Network error.")};
          xhr.onload = function() {
              if (xhr.status === 200) {resolve(xhr.response)}
              else {reject("Loading error:" + xhr.statusText)}
          };
          xhr.send();
      }
      catch(err) {reject(err.message)}
    })
  }

uploadToFirebase = (blob) => {
    console.log('uploading to firebase')
    return new Promise((resolve, reject)=>{
      var storageRef = firebase.storage().ref();
      storageRef.child('uploads/photo.jpg').put(blob, {
        contentType: 'image/jpeg'
      }).then((snapshot)=>{
        blob.close();
        resolve(snapshot);
      }).catch((error)=>{
        reject(error);
      });
    });
  }

按下按钮后,我运行以下代码:

this.uriToBlob(this.state.imageUri).then(function(blob) {
      return this.uploadToFirebase(blob)
    });

但是,我总是得到错误

[未处理的承诺拒绝:TypeError: undefined is not an object (evalating 'this.uploadToFirebase')]

我之前没有使用过 Firebase 存储或 blob,因此我非常感谢您了解为什么这不起作用。谢谢!

【问题讨论】:

    标签: javascript firebase react-native expo firebase-storage


    【解决方案1】:

    问题出在这里:

    this.uriToBlob(this.state.imageUri).then(function(blob) {
      return this.uploadToFirebase(blob)
    });
    

    您没有使用箭头函数,因此“this”实际上不是您要查找的上下文(来自父范围的上下文)。

    你应该这样做:

    this.uriToBlob(this.state.imageUri).then((blob) => {
      return this.uploadToFirebase(blob);
    });
    

    【讨论】:

    • 完美运行!非常感谢。
    猜你喜欢
    • 2018-12-25
    • 2022-01-08
    • 1970-01-01
    • 1970-01-01
    • 2017-01-11
    • 1970-01-01
    • 2023-02-24
    • 2020-03-06
    相关资源
    最近更新 更多