Search code examples
vuejs2google-cloud-storagefilereader

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


I am trying to use the FileReader() API and having trouble understanding how to wait for it to finish so that way I can access the data URL and upload it to cloud storage.

Let me explain:

I have the following template:

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

Script:

    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

Here is screenshot of console error: enter image description here

How can I successfully await for the file reader to finish before running the .putString() ? Thank you!


Solution

  • You can utilize a Promise and then use async await like below :

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