Как кодировать изображение в base64 в <q-uploader>? - PullRequest
0 голосов
/ 21 апреля 2019

Я только начинаю изучать Квазар (и Вью).Я пытаюсь закодировать изображение в 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)
        })
    }

1 Ответ

0 голосов
/ 25 апреля 2019

Вот как вы можете получить файл в q-uploader в строку base64. Оттуда вы сможете понять, как вставить эту строку в вашу базу данных.

1) Добавить имя ссылки в q-uploader. (Я использую "файлы")

<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 и обещания являются ключевыми здесь. В противном случае файл reader.onload может не запуститься до того, как вы попытаетесь использовать вывод.

4) Вызовите свою функцию, используя код из шага 2

encodeToBase64(this.$refs.files.files)

Примечание: я написал это, чтобы отразить наличие нескольких файлов в q-uploader, поскольку с асинхронностью, ожиданием и обещаниями может быть сложно разобраться.

Примечание: я мог бы, вероятно, избавиться от массива reader и просто объявить его как обычный считыватель в методе singleFileToBase64 ... но я не проверял это.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...