Using VueJs and typescript, transform the input image into Base64 format

Welcome to my first question on this platform!

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

Here is the current issue I am facing:

The line e.target.files[0] keeps showing as possibly null, causing const selectedImage and this.picture not to be retrieved.

<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>

Your help with this matter will be greatly appreciated. Thank you in advance!

Answer №1

If you want to make a change, consider replacing reader.readAsBinaryString(fileObject) with reader.readAsDataURL(fileObject) within the createBase64Image function.

Another helpful tip is to utilize 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>

For more information, visit: https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL

Answer №2

It's important to remember that the onchange event might not always ensure that e.target.result is not null. It's a good practice to include this check:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with V-checkbox input-value not triggering correctly on change

Query Example: <query #[`${instanceItemIdKey}`]="{ item }"> <v-checkbox :input="item.content" @modify="$notify('onPermissionUpdate', item)" ></v-checkbox> </query> The information that influ ...

The logic behind regular expressions

Currently working on building a web application with Angular 6 and I have a query: I'm in the process of developing a custom input component (specifically for text inputs) like so: @Component({ selector: 'input-text', templateUrl: &apos ...

Disable Nuxt Auth from sending the authorization header to an external URL

I am facing a challenge in my project as I need to send a POST request to an external API using axios within a nuxt application that utilizes the nuxt auth module. When a user is authenticated, axios automatically includes an authorization header which is ...

Ways to retrieve form data from a dynamic CDKPortalComponent

I have a dynamic cdkportal component that is created from a variety of Components. These components are added to a modal dialog, and I need to determine the validity of the forms within them. If any of the child component forms are invalid, I want to disab ...

Showing a Bootstrap.vue b-table containing nested arrays within arrays

I am facing an issue while trying to display data in a b-table. Normally, it works well with most data sets. However, when I encounter another array nested within the referenced array, the rendering is not done properly. While working on this problem, I ...

Switching elements in an array using Vue.js

Within my vue.js web application, I am attempting to switch the positions of two rows in a forum. Below is the code snippet I am using: export default { data() { return { forums: [] } }, met ...

Angular 11 is indicating that the type 'File | null' cannot be assigned to the type 'File'

Hey there, I'm currently diving into Angular and I'm working on an Angular 11 project. My task involves uploading a CSV file, extracting the records on the client side, and saving them in a database through ASP.NET Web API. I followed a tutorial ...

Calling GraphQL mutations in ReactPGA

I encountered a 400 Error when making a call from the client to server, and I'm not sure where to start troubleshooting. Oddly enough, when I only include the "id" parameter in the request, everything works fine. However, as soon as I add the additio ...

The query parser in MongoDB encounters an issue when trying to parse a 2dsphere query with two conditions

My Collection currently contains the following object: { "_id":"test123", "footprint":{ "type":"Polygon", "coordinates":[ [ [10, 30], [20, 45], [38, 38], [43 ...

Tips for compacting JSON in Typescript

I have encountered a challenge in my coding where we are dealing with quite large data objects. I am exploring the possibility of compressing these data objects to reduce payload size. For instance, if our input json size is 2 MB, can it be compressed to a ...

How can I capture the click event on the oktext in Ionic?

When using Ionic, I have a select button with options for okText and cancelText. The issue I am facing is that when I click on okText, the menu closes as expected due to this attribute. However, I am interested in implementing it through click events. Belo ...

What is the reason behind VueJs not having built-in support for multiple select options?

Recently delving into the world of vue, I encountered a challenge while working on an update form. When trying to pre-select multiple options using the selected attribute, I noticed that only the last option was being selected. Upon further investigation, ...

The operation in Mongo DB carried out a $pull to eliminate the ObjectId("... id") from the nested sub-array

I've scoured every nook and cranny of the internet in an attempt to resolve this issue, but so far I've come up empty-handed. My goal is to use the mongodb $pull function to remove an Object from an array nested inside a Schema. I've success ...

Trigger parent Component property change from Child Component in Angular2 (akin to $emit in AngularJS)

As I delve into teaching myself Angular2, I've encountered a practical issue that would have been easy to solve with AngularJS. Currently, I'm scouring examples to find a solution with Angular2. Within my top-level component named App, there&apos ...

Issue when transferring properties of a component to a component constructed Using LoadingButton MUI

Check out my new component created with the LoadingButton MUI: view image description here I'm having issues passing props to my component: view image description here Dealing with a TypeScript problem here: view image description here I can resolv ...

Module augmentations do not allow for exports or export assignments

import { Request as ExpressRequest, Response as ExpressResponse } from 'express'; declare module 'kvl' { export = kvl; } declare const kvl: { ValidationDone:(param:(error: any, response: ExpressResponse) => void) => void; ...

A comprehensive tutorial on VueJS version 2. Exploring the power of v-model with non-value

I am currently working through the VueJS guide and exploring https://v2.vuejs.org/v2/guide/components.html#Customizing-Component-v-model. I attempted to create a simple example but have not been successful in getting it to function. What modifications do ...

The UI elements are failing to reflect the changes in the data

In an attempt to establish communication between three components on a webpage using a data service, I have a Create/Edit component for adding events, a "next events" component for accepting/declining events, and a Calendar component for displaying upcomin ...

Retrieve model from MongoDB using mongoose

I am in the process of developing a small RESTful service that allows me to input data into a mongoose database using POST and retrieve the data using GET. Below is my main.js file: var http = require("http"); var DAO = require("./DAO"); var express = re ...

Steps for redirecting to a 404 page using vue-router when encountering an invalid URL parameter

Utilizing vue-router, I am able to direct users to specific pages based on their user id. The configuration in the router.js file is structured as shown below: export default new Router({ mode: 'history', base: process.env.BASE_URL, rou ...