Vue 和 FileReader API:如何在上传前等待图像文件?

Vue and FileReader API: How to wait for image file before uploading?

我正在尝试使用 FileReader() API 并且无法理解如何等待它完成以便我可以访问数据 URL 并将其上传到云存储。

让我解释一下:

我有以下模板:

      <input
        id="my-file-input"
        type="file"
        accept="image/*"
        @change="fileChangeHandler"
      />
     <img src="photo" />

脚本:

    fileChangeHandler(e) {
      const reader = new FileReader()
      reader.onload = (e) => {
        this.photo = e.target.result
      }
      reader.readAsDataURL(e.target.files[0])
      console.log(this.photo)
      
      const file = this.photo
      // convert photo file name to hash
      const photoName = uuidv4()
      const storageRef = this.$fireStorage.ref()
      const photoRef = storageRef.child(
        `photos/${this.userProfile.uid}/${photoName}/${photoName}.jpg`
      )
      const uploadTask = photoRef.putString(file, 'data_url') <--- image not ready yet, thus get console error

控制台错误截图如下:

如何在 运行 .putString() 之前成功等待文件 reader 完成?谢谢!

您可以使用 Promise,然后使用 async await,如下所示:

async fileChangeHandler(e) {      
  this.photo = await new Promise(resolve=>{ 
   const reader = new FileReader()
   reader.onload = (e) => {
        resolve(e.target.result)
      }
  });
   // rest of your code
}