Home > database >  Convert input image to Base64 using VueJs and typescript
Convert input image to Base64 using VueJs and typescript

Time:05-19

This is my first question here.

I would like to convert an input file(image) from a form using VueJs 3 and typescript to Base64 to "send" it to my backend (java, spring boot) and store it in mongodb as a part of a "User" model

Here's what I have:

The line e.target.files[0] keeps saying that it's possibly null.. so the const selectedImage and this.picture won't get them.

<template>
<v-file-input
  @change="handleImage"
  type="file"
  accept="image/*"
  label="File input"
  v-model="picture"
  filled
  prepend-icon="mdi-camera"
></v-file-input>
</template>
<script lang="ts">
interface State {
picture: string;
}

data: (): State => {
return {
picture: "",
  }
}
methods: {
handleImage(e: Event) {
      const selectedImage = e.target.files[0];
      this.createBase64Image(selectedImage);
    },
    createBase64Image(fileObject: File) {
      const reader = new FileReader();
      reader.onload = (e) => {
        this.picture = e.target.result;
      };
      reader.readAsBinaryString(fileObject);
    },
},
</script>

Thank you in advance for your help!

CodePudding user response:

You could change reader.readAsBinaryString(fileObject) in the createBase64Image function to reader.readAsDataURL(fileObject)

Also something that would help is to use refs in your component

<template>
<v-file-input
  @change="handleImage"
  type="file"
  accept="image/*"
  label="File input"
  v-model="picture"
  filled
  prepend-icon="mdi-camera"
  ref="file"
></v-file-input>
</template>

<script lang="ts">
interface State {
picture: string;
}

data: (): State => {
return {
picture: "",
  }
}
methods: {
    handleImage(e: Event) {
      const selectedImage = this.$refs.file.files[0];
      this.picture = this.createBase64Image(selectedImage);
    },
    createBase64Image(fileObject: File) {
      const reader = new FileReader();
      return reader.readAsDataURL(fileObject);
    },
},
</script>

Additional Information:

https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL

CodePudding user response:

I think onchange event doesn't guarantees e.target.result to be non-null. Do this check:

if (e.target && e.target.files.length > 0)
  • Related