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

Angular: Identifier for Dropdown with Multiple Selection

I have recently set up a multi select dropdown with checkboxes by following the instructions provided in this post: https://github.com/NileshPatel17/ng-multiselect-dropdown This is how I implemented it: <div (mouseleave)="showDropDown = false" [class. ...

The property 'label' is not found in the 'string' type in Typescript

Below is the code snippet I am using: interface State { resourceGroup: QuickPickItem | string; } setEvent(state.resourceGroup?.label).catch(err => console.error(err)); When executing this code, I encountered the following error messa ...

The basic jQuery script is failing to function properly in the Opera browser

I've encountered an issue with a simple jQuery script I wrote. It seems to work fine on most browsers, except for Opera. Can anyone help me figure out what the problem might be? jQuery(document).ready(function() { jQuery("input:radio[name=virtuem ...

Struggling to get the Ant design button to launch an external link in a new tab using React and NextJS

I have an Ant button set up like this: <Button style={{ borderRadius: '0.5rem' }} type="default" target="_blank" ...

An option selection component for Vue.js

I'm attempting to design a component like the following: <template> <option v-for="(text, value) in options" :value="value"> {{ text }} </option> </template> Unfortunately, I encountered an error me ...

Emberjs: Developing a self-focusing button with Views/Handlebar Helpers

Currently, I am using a Handlebars helper view that utilizes Em.Button (although it's deprecated) to create a Deactivate Button. This button is designed to focus on itself when it appears and clicking it triggers the 'delete' action. Additio ...

Persistent hover state remains on buttons following a click event

In my current project, I am dealing with a form that has two distinct states: editing and visible. When the user clicks on an icon to edit the form, two buttons appear at the bottom - one for saving changes and one for canceling. Upon clicking either of th ...

Efficient techniques for extracting data from several forms simultaneously

I've set up dropzone js for drag and drop file uploads in Django. For this, I needed to use a Django form with the dropzone class. Since I also wanted users to add text information, I ended up creating two forms in Django - one for the dropzone upload ...

Dealing with encoded base64 audio and retransmitting it to Google: a comprehensive guide

I managed to successfully capture audio using the browser's microphone, convert it to base64 encoding, and then sent it over to my node.js application with the intention of further processing it through Google Speech-to-Text API for transcription. How ...

Installing Vue JavaScript using the npm command

Embarking on my journey as a Vue JS learner, I took the plunge to install Vue and delve into creating web applications using it. So, I globally added npm Vue. npm install --global vue-cli This action resulted in: npm WARN deprecated [email protected]: T ...

Guide to implementing PCF (SOFT) shadows with three.js

Is it possible to apply the PCF (SOFT) shadow type, like the one found in the Three.js online editor, to your renderer using javascript code? https://i.sstatic.net/x0QmH.png ...

What is the best method for showcasing various content using a uniform accordion style in React?

What is the most efficient way to display various content within multiple accordions? view image description here This is the current approach I am taking in my project, where shipping information and delivery options will involve different textboxes, labe ...

Creating a horizontal scrolling section for mobile devices using CSS

Looking to create a horizontal scroll area specifically for mobile devices, similar to the design seen here: https://i.sstatic.net/oSNqL.png Additionally, I want to hide the scrollbar altogether. However, when attempting to implement this, there seem to ...

CSS-enabled tabs built with React

Currently, I have a setup with 5 divs and 5 buttons where only one div is visible at a time when its corresponding button is clicked. However, I am looking for suggestions on how to improve the efficiency and readability of my code. If you have any best pr ...

Having trouble with my JSFiddle code not functioning properly in a standard web browser for a Google Authenticator

Here is the code snippet that I am having trouble with: http://jsfiddle.net/sk1hg4h3/1/. It works fine in jsfiddle, but not in a normal browser. I have included the necessary elements in the head to call all the external files. <head> <scri ...

Are there alternative methods for retrieving data in Vue Hacker News besides using prefetching?

I am currently developing a Vue single page application with server side rendering using Vue SSR. As per the official documentation, data in components will be prefetched server-side and stored in a Vuex store. This process seems quite intricate. Hence, ...

Is it possible to execute "npm run dev" for vue3 within a docker environment?

I am trying to set up a Vue project using a Node image inside a Docker container. However, after running "docker-compose up --build -d", I am not seeing any logs in the Docker container or terminal, and the server is not starting. Below is my DockerFile: ...

Guide on merging non-modular JavaScript files into a single file with webpack

I am trying to bundle a non-modular JS file that uses jQuery and registers a method on $.fn. This JS must be placed behind jQuery after bundling. Here is an example of the structure of this JS file: (function($){ $.fn.splitPane = ... }(JQuery) If y ...

How should v-select, item-text, and item-value be correctly utilized?

When I make an API call, the response is returned. from another perspective. I store the result of the API call in a variable called result = [];. To create a dropdown list, I use v-select with :items="result". If I want the services.name to ...

w3schools example showcasing the power of AJAX

How can I run this example on my local machine? http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_httprequest_js (page no longer available) I want to access the XML file hosted on w3schools without moving it to my machine. Can I run the HTML and J ...