Get the png image file and display a preview of it

Within my template, I have an img tag that is linked to a state known as "imageBuffer"

 <img v-bind:src="imageBuffer" alt="" />

In the logic of the page, there are two file inputs and I've utilized a single function to manage file selection:

onFilePicked(event, type) {
      const extension = this.getExtension(event.target.files[0].name);
      let isValid = false;

      if (type === 'pdf' && extension === 'pdf') {
        isValid = true;
      }

      if (type === 'image' && (extension === 'jpg' || extension === 'png')) {
        isValid = true;
      }

      if (isValid) {
        const fileReader = new FileReader();
        if (type === 'pdf') {
          const files = event.target.files;
          let filename = files[0].name;
          fileReader.addEventListener('load', () => {
        });

          this.pdf = files[0];


        } else if (extension === 'png' || extension === 'jpg') {

          fileReader.addEventListener('load', () => {
            this.imageBuffer = fileReader.readAsDataURL(event.target.files[0]);
          });

        }
      } else {
        alert('Invalid file type');
      }
    },

The PDF selector is functioning correctly. However, when I check the console log for "imagebuffer", it appears to be malfunctioning as the image preview isn't displaying. Which FileReader method should I employ in order to retrieve the image buffer and convert it into a png format?

Answer №1

Your file reader won't trigger the load event unless you instruct it to read something first.

Take a look at the readAsDataURL method for guidance. There's a helpful example on that page as well.


You'll need to adjust your code a bit:

fileReader.addEventListener('load', () => {
    // imageBuffer now contains the dataURL from the uploaded file
    this.imageBuffer = fileReader.result;
});
// Load the file selected by the user
fileReader.readAsDataURL(event.target.files[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

Retrieving table information using javascript

My goal is to retrieve information from the <td> elements within the following HTML table: <table class="datadisplaytable" summary="This table lists the scheduled meeting times and assigned instructors for this class.."> <caption class="cap ...

Canvas ctx.drawImage() function not functioning properly

I've encountered an issue while trying to display images in a canvas using my rendering function. Here is the code snippet: function populateSquareImages(){ for(var i = 0, ii = squares.length; i < ii; i++) { if(squares[i].hasImage) { ...

Angular directive ceases to trigger

I am currently working on implementing an infinite scrolling directive. Initially, when the page loads and I start scrolling, I can see the console log. However, after the first scroll, it stops working. It seems like it only triggers once. Can anyone poi ...

Unresolved promise rejection on Repl.it

I decided to add a basic leaderboard feature to my game on Repl.it, so I set up a node.js backend for it. Here's the code snippet for the backend: const express = require('express'); const Client = require('@replit/database'); cons ...

React is struggling to locate the specified module

Once I've set up my react project using npx create-react-app called my-app, I proceed to run npm start only to encounter the error shown in the image below. Running node version: 12.16.1 with npm version: 6.13.4 View the error message her ...

The content is not visible following the quotation mark

Once my script is executed, the input field ends up looking like this: <input type="text" value="How do you " /> Even if I try to escape the quotes or change them to &quot;, it still doesn't seem to work. Do you have any suggestions? $(& ...

Problem with Bootstrap 3 navbar on mobile devices - not tappable or responsive

After years of using Bootstrap, I've come across a new issue with my implementation of a Bootstrap 3 Nav. While testing on a desktop browser with device emulation, the nav collapses and functions properly. However, when tapping on the header on an ac ...

Storing socket.io data in an array

Having trouble getting the desired array of arrays from my socket.io emitter. The structure I need is: [ [{...},{...},{...}] , [{...},{...}] , [{...}] ] But instead, I am receiving a different format. https://i.stack.imgur.com/3PY0u.jpg I require all t ...

The v-navigation-drawer component in Vuetify 2 is not reappearing after setting dialog to false

I am utilizing the navigation drawer to display my data list in a dialog box. Everything works fine when I initially open it, however, upon reopening the dialog, the entire navigation drawer vanishes. The data GET operation is functioning correctly with no ...

Margin ambiguity in a vue.js application

I am facing an issue with my Vue.JS project setup. I want the App.vue to occupy the entire page and have different routes displayed within App.vue using router-view. But, when I try to add a margin to the content of my Game component, the margin seems to ...

What could be causing the routing to fail in this script?

Currently working on a small project to dive into AngularJS, and I'm facing some challenges with getting the routing to function properly. Despite following numerous tutorials, my code doesn't seem to be working as expected. If anyone could lend ...

Inconsistency with Mobile Viewport Problem

Apologies for the chaos below, but I've spent quite some time attempting to fix this on my own. It's time to surrender and seek assistance! Here are some screenshots to illustrate the issue: The problem is that sometimes the webpage functions c ...

Methods for establishing state within a React Native render function

I encountered an issue when attempting to set state within the render lifecycle. Warning: It is not recommended to update state during an ongoing state transition, such as in the render method or another component's constructor. The render method s ...

Encountering error TS2307 while using gulp-typescript with requirejs and configuring multiple path aliases and packages

Currently, I am working on a substantial project that heavily relies on JavaScript. To enhance its functionality, I am considering incorporating TypeScript into the codebase. While things are running smoothly for the most part, I have encountered an issue ...

Unable to provide any input while utilizing npm prompts

After installing npm prompts, I encountered a strange issue. When trying to run the example code for npm prompts, I found that I couldn't enter any input at all. The underscore in the input field would blink for a few seconds, then the cursor would ju ...

Develop a cross-platform application using webpack for both web browsers and Node.js

I'm currently developing my first module, and the code is almost identical for both browser and node.js versions. The only variance lies in the use of XmlHttpRequest for the browser and the http module for node.js. Here's a sample code snippet t ...

Jpicker is renowned for its transparency feature

I am currently using the Jpicker jpicker-1.1.6.js script which can be found at Below is a snippet of my code: <script type="text/javascript"> $(function() { $.fn.jPicker.defaults.images.clientPath='/img'; var ...

The data type 'boolean' cannot be assigned to the type 'CaseReducer<ReportedCasesState, { payload: any; type: string; }>'

I recently developed a deletion reducer using reduxjs/toolkit: import { createSlice, PayloadAction } from "@reduxjs/toolkit"; import { AppThunk } from "../store"; import { ReportedCase, deleteReportCase } from "../../api/reportedCasesApi"; import history ...

Obtaining the most recently inserted ID in Node.js can be achieved by using

Currently in my Nodejs project, I am using the expressjs framework. I am facing an issue where I am trying to retrieve the "last inserted id", but it is showing as "undefined" in the console. How can I successfully get the last inserted id? Below is the ...

Utilize AJAX JQuery to Transmit POST Data

I am facing an issue with sending the selected item from a Bootstrap dropdown to my controller using the POST method. Unfortunately, I am encountering difficulties in getting it to work. Within the dropdown, I am fetching records from the database and dis ...