【问题标题】:Firebase storage wont allow me to retreive image URLFirebase 存储不允许我检索图像 URL
【发布时间】:2020-09-26 12:44:00
【问题描述】:

我成功地将文件上传到 Firebase 存储。

但是,当我在 statechanged 中包含 .on 函数时,控制台会抛出以下错误:

错误:Reference.push 失败:第一个参数在属性“testimonials.clientImg”中包含未定义

我正在尝试检索图像 URL 并将其放入变量中。

我的代码如下所示,有人可以帮忙吗?

  let itemsRef = firebase.database().ref('testimonials');
  let imgFile = this.state.currentImg;
  let imageRef;
  let imgURL;

  if (imgFile){
   imageRef = firebase.storage().ref("testimonialPics/"+imgFile.name).put(imgFile);


   imageRef.on('state_changed', (snapshot)=>{
    console.log(snapshot);
   })

  let clientObj = {
    name: this.state.currentName,
    feedback: this.state.currentComments,
    approved: false,
    clientImg: imgURL
  }

  itemsRef.push(clientObj);
  console.log(clientObj);

  this.setState({
    currentName: "",
    currentComments: "",
    currentImg: null
  })

【问题讨论】:

  • 无代码。您共享呼叫push(),因此该错误不太可能来自此代码。请仔细检查错误消息和堆栈跟踪,将它们包含在您的问题中,并确保我们拥有引发错误的代码。
  • 嗨@FrankvanPuffelen 我没有包含似乎触发错误的推送方法
  • 您没有在此代码中的任何位置给 imgURL 一个值,这与您调用 itemsRef.push(clientObj) 时它是 undefined 的事实相匹配,并且(如错误消息所述,您可以'不要将未定义的值写入数据库。

标签: javascript firebase firebase-realtime-database firebase-storage


【解决方案1】:

您没有在此代码中的任何地方给 imgURL 一个值,这与您调用 itemsRef.push(clientObj) 时它是 undefined 的事实相匹配,并且(如错误消息所述,您不能编写未定义的对数据库的价值。

您似乎正在尝试将下载 URL 写入数据库。为此,我会密切关注example in the documentation。但根据您当前的代码,它应该是这样的:

  let itemsRef = firebase.database().ref('testimonials');
  let imgFile = this.state.currentImg;
  let imageRef;
  let imgURL;

  if (imgFile){
   let ref = firebase.storage().ref("testimonialPics/"+imgFile.name); 
   let task = ref.put(imgFile);
   task.then(() => {
    // this runs when the upload has completed
    ref.getDownloadURL().then(function(downloadURL) {
      // this runs when the download URL has been determined
      let clientObj = {
        name: this.state.currentName,
        feedback: this.state.currentComments,
        approved: false,
        clientImg: downloadURL
      }

      itemsRef.push(clientObj);

      this.setState({
        currentName: "",
        currentComments: "",
        currentImg: null
      })
    })
  })

【讨论】:

    【解决方案2】:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-23
      • 1970-01-01
      • 2017-07-02
      • 1970-01-01
      • 2020-10-23
      • 2017-08-30
      • 2020-07-10
      相关资源
      最近更新 更多