如何在 <q-uploader> 中将图像编码为 base64?

How to encode image to base64 in <q-uploader>?

我刚开始学习 Quasar(和 Vue)。我正在尝试将图片编码为 Base64 并保存到 MongoDB。 下面提到的代码适用于该组件,但我无法为该组件重做。 如果有任何帮助,我将不胜感激

<q-uploader v-model="image" @change="encodeToBase64" />
<q-btn type="btn" @click="sendPhoto">Save photo in mongo and go next page</q-btn>
methods: {
    encodeToBase64 (event) {
      event.preventDefault()
      const file = event.target.files[0]
      const canvas = document.createElement('canvas')
      const ctx = canvas.getContext('2d')
      const reader = new FileReader()
      reader.onload = event => {
        const img = new Image()
        img.onload = () => {
          if (img.width > MAX_WIDTH) {
            canvas.width = MAX_WIDTH
            canvas.height = (MAX_WIDTH * img.height) / img.width
          } else {
            canvas.width = img.width
            canvas.height = img.height
          }
          ctx.drawImage(img, 0, 0, canvas.width, canvas.height)
          this.image = canvas.toDataURL('image/png').replace(/^data:image\/(png|jpg);base64,/, '')
          console.log('RESULT/png', this.image)
        }
        img.src = event.target.result
        console.log('RESULT!', img.src)
      }
      reader.readAsDataURL(file)
    }
}
sendPhoto (event) {
      event.preventDefault()
      this.$store.dispatch('image/create', {account_id: this.account_selected, image: this.image})
        .then((res) => {
          this.$router.push({'path': '/nextReadings/' + res._id})
        })
        .catch((err) => {
          err.message = 'Error message'
          this.errorHandler(err.message)
        })
    }

以下是如何将 q-uploader 中的文件转换为 base64 字符串。从那里您应该能够弄清楚如何将此字符串插入到您的数据库中。

1) 给q-uploader 添加一个ref name。 (我正在使用 "files")

<q-uploader ref="files" label="My Label" :additional-fields="[{name: 'name', value: 'value'}]" multiple/>

2) 您现在可以通过

随时获取q-uploader中的文件
this.$refs.files.files

3) 创建以下两个函数。这是我找到的将 javascript 文件转换为 base64 的最简洁和简单的方法。

async encodeToBase64(files) {
  var attach = [];
  var reader = [];

  // loop through each of the files in q-uploader
  for (let i = 0; i < files.length; i++) {
      attach[i] = await this.singleFileToBase64(i, files, reader)
  }
  // returns an array of all the files in base64 format
  return attach;
},

singleFileToBase64(i, files, reader) {
    reader[i] = new FileReader();   
    // read the file into a base64 format 
    reader[i].readAsDataURL(files[i]);

    return new Promise((resolve, reject) => {
        reader[i].onerror = () => {
            reader[i].abort();
            reject("Insert error message here")
        };

        // return the base 64 string
        reader[i].onload = function () {
            resolve(reader[i].result);
        };
    })
},

注意:这里使用 async、await 和 promises 是关键。否则 reader.onload 在您最终尝试使用输出之前可能没有 运行。

4) 使用步骤 2 中的代码调用您的函数

encodeToBase64(this.$refs.files.files)

注意:我写这篇文章是为了反映 q-uploader 中有多个文件,因为使用 async、await 和 promises 可能很难弄清楚。

注意:我可能会去掉 reader 数组,并在 singleFileToBase64 方法中将其声明为普通的 reader...但我还没有测试过。