How to encode image to base64 in q-uploader?
-
I’m just starting to learn Quasar (and Vue). I’m trying to encode a picture into a Base64 and save to MongoDB.
Undermentioned code works for the component <inpute> but I can’t redo it for the component <q-uploader>.
I will be thankful for any help<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) }) }
-
@nomad you can use
factory
props https://v1.quasar-framework.org/vue-components/uploader#Example--Promise-based-factory-function or convert the file to base64 in your consuming api before inserting it in your mongodb (this is probably better). what you posted above though is best suited for a customized input component w/ type of file, as q-uploader has its own api.here’s a mock test converting base64 in client side using
factory
prop of q-uploader https://codepen.io/metalsadman/pen/YMvEbr?editors=1011 check browser console for the converted base64 data. -
@metalsadman thank you))) it helped me