VueJS 和 Firebase 存储:如何等到图像上传完成后再将 URI 提交到数据库?

我构建了一个评论系统,允许用户在评论中添加图像。我试图等到图像上传完成后再向 firestore 添加评论,但我的尝试不起作用。我有一个名为photoUpload()将图像上传到 firebase 存储的方法。该方法包含一个uploadTask用于获取进度详细信息的侦听器。但是,在图像上传完成之前,我的评论已添加到数据库中。


如何延迟并等到完成后再提交评论?


这是我的代码:


数据功能:


  data() {

    return {

      text: '',

      image: null,

      overlayShow: false,

      progress: 0,

      downloadUrl: null

    }

  },

这是我的图片上传任务:


photoUpload() {

  this.filename = uuidv4()

  const storageRef = this.$fireStorage.ref()

  this.photoRef = storageRef.child(

    `photos/${this.userProfile.uid}/commentPhotos/${this.filename}`

  )

  // uploads string data to this reference's location

  const uploadTask = this.photoRef.putString(this.image, 'data_url')


  // set the callbacks for each event

  const next = (uploadTaskSnapshot) => {

    this.progress =

      (uploadTaskSnapshot.bytesTransferred /

        uploadTaskSnapshot.totalBytes) *

      100

    console.log('Upload is ' + this.progress + '% done')

  }

  const error = (error) => {

    ...snijp...

  }

const complete = async () => {

    // Upload completed successfully, now we can get the download URL

    this.downloadUrl = await uploadTask.snapshot.ref.getDownloadURL()

  }

  // listens for events on this task

  uploadTask.on(

    // 3 callbacks available for each event

    this.$fireStorageObj.TaskEvent.STATE_CHANGED,

    {

      next,

      error,

      complete

    }

  )

}

梵蒂冈之花
浏览 102回答 1
1回答

holdtom

您应该进行uploadComplete异步,并返回一个承诺,该承诺仅在上传完成且下载 URL 可用后才解决。由于它的所有工作都是异步的,因此您必须构建一种方法让调用者知道这一点,否则该函数将在任何操作完成之前立即返回。如果您还等待等待 uploadTask (它的作用就像一个承诺)来知道它何时完成,而不是使用回调,那么可能会更容易。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript