首页 > 解决方案 > Vue 和 FileReader API:如何在上传之前等待图像文件?

问题描述

我正在尝试使用 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()?谢谢!

标签: vuejs2google-cloud-storagefilereader

解决方案


您可以使用 aPromise然后使用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
}

推荐阅读