Obtain the string value of `reader.result` from the `FileReader

Struggling to retrieve a string in a reader.onloadend but it's constantly returning my entire function. Here is the function I'm using:

uploadFile() {
      let vm = this;
      var file = vm.$refs["testeLogo"].files[0];
      var reader = new FileReader();
      reader.onloadend = function() {
        console.log(reader.result); // returns me a string base64
        document.querySelector("#supe").setAttribute("src", this.imagem);
        return reader.result;
      };
      reader.readAsDataURL(file);
    }

Looking for advice on how to successfully fetch and return the string value, as it currently seems to be returning my function instead of the expected reader.result displayed in the console.log.

Answer №1

If you are currently working on a Vue application (please inform me if you are not):

Simply utilize the imageBase64 variable wherever needed within your template, it will automatically update once the file has been loaded.

data () {
  return {
    imageBase64: ''
  }
},

methods: {
  uploadFile() {
    let vm = this;
    var file = vm.$refs["testeLogo"].files[0];
    var reader = new FileReader();

    reader.onloadend = function() {
      document.querySelector("#supe").setAttribute("src", this.imagem);
      
      vm.imageBase64 = reader.result
    };

    reader.readAsDataURL(file);
  }
}

Furthermore, keep in mind not to directly manipulate the DOM when using Vue. Instead, bind the imagem variable directly to the img src attribute:

<img :src="imagem" alt="" />

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

Is there a way to set up a vue-good-table to automatically switch to the next page every 5 seconds?

I came across an example of a vue-good-table in one of their tutorials, but I have a unique requirement. I want the table to automatically move to the next page every 5 seconds, and when it reaches the end, restart back at page 1. How can this be achieved? ...

waiting to display information until it is necessary

I am currently working on optimizing my website for improved loading speed and responsiveness. Users can scroll through up to 4k images, apply filters, and sort them based on their preferences. Below is the code snippet for my filtering function: function ...

How to Convert JSON from an Object to a String using jQuery?

Currently, I am utilizing the Ajax Form jQuery plugin to fetch JSON data from a server: /** * A convenient function for the jQuery AJAX form plugin. */ function bindOnSuccess(form, callback) { form.ajaxForm({ dataType: 'json', ...

What are the best practices for managing images (uploading, deleting, etc.) within the CakePHP framework?

I am in the process of developing a website where users can upload images for use. I would appreciate some feedback and suggestions on how to effectively manage temporary uploads. For instance, if a user uploads an image but then decides not to utilize it ...

Using Firebase to interact with data: $add(), .push(), and .set()

Utilizing Firebase and AngularFire has opened up many different approaches for CRUD operations with the Firebase API. However, I am still uncertain about the specific differences between using: $add with $firebaseArray The .push() method The .set() metho ...

Managing the re-rendering in React

I am encountering a situation similar to the one found in the sandbox example. https://codesandbox.io/s/react-typescript-fs0em My goal is to have Table.tsx act as the base component, with the App component serving as a wrapper. The JSX is being returned ...

Error: Unable to access the 'length' property of an undefined value | Solving the challenge of finding the shortest word within a string | Codewars Problem

I'm currently working on a function to find the shortest word in a given string of words. Issue: I encountered the error below TypeError: Cannot read property 'length' of undefined at findShort at Test.describe._ at /runner/fra ...

What is the best way to eliminate a vertical line from the canvas in react-chartjs-2?

Can someone please lend me a hand? I've been working on a project in React JS that involves using react-chartjs-2 to display charts. I'm trying to incorporate a range slider for the chart to manipulate values on the x-axis, as well as two vertic ...

Creating a Dynamic Login Panel Using HTML, CSS, and Jquery

Designing a dynamic sliding login panel utilizing Html, CSS, and jquery alongside various plugins. Check it out here: http://24.125.42.135/ When activated, the bar smoothly pushes down the content (click on the login option at the top right corner). This ...

When attempting to retrieve the data from a JSON file using an XMLHttpRequest, the result that is returned is [object object]

I am currently studying JSON and found a helpful guide on w3schools. Here is the code provided in the guide: https://www.w3schools.com/js/tryit.asp?filename=tryjson_ajax The guide also includes a sample JSON file: https://www.w3schools.com/js/json_demo.t ...

using app.use to directly pass arguments without delay (NODE.JS)

I'm currently figuring out why the code 1 is functioning properly, while the code 2 is not... app.js: // Implementing Routes var server = require('./routes/server'); app.use('/', server); Route.js: var express = require(&a ...

React doesn't have file upload configured to update the state

I am working on integrating a file upload button that sends data to an API. To ensure only the button triggers the upload dialog and not the input field, I have set it up this way. Issue: The File is not being saved to state, preventing me from using a ...

Incorporate a button into each row of a b-table by utilizing a template

I am attempting to include a button in each column of my table using a Vuejs template. I have successfully added the Actions column, but unfortunately the button is not displaying. It seems like I might be overlooking something. <template> <div ...

What is the best way to retrieve the previous state of a file field in React?

Currently, I am working on implementing an on-change handler for an audio file in a component. The goal is to load the previous state of the file when the user changes it and records the new path. Specifically, when the user enters the component, the file ...

What is the process for uploading files using AngularFire on Firebase Storage?

Despite watching multiple videos and tutorials, I am encountering a 403 error while working with Angular 1. To solve the issue of ng-model not supporting files, I created an Angular directive named file-model: app.directive('fileModel',['$ ...

The dimensions of the image are determined by its orientation

I am working with two different types of images on my website: vertical and horizontal. Currently, I have a JavaScript function that adjusts the height of all images to fit the screen size. However, I would like to modify this function so that it also adap ...

The type 'undefined' cannot be assigned to the type 'string | Buffer | { key: string | Buffer; passphrase: string; } | GetPublicKeyOrSecret'

Verification Code for JWT This function is used to verify a jwt using typescript. public verify( token: string, secretOrPublicKey?: string | Buffer, options?: jwt.VerifyOptions ): Promise<object | string> { if (!secretOrPublicKey) { ...

[Web Development]:

Having an issue with my HTML file where a JavaScript function named "CheckCaptcha" is not being executed when an image is clicked. I've been working on the code for hours, trying different tweaks and modifications, but it still can't seem to find ...

Tips for recalling the display and concealment of a div element using cookies

My HTML code looks like this: <div id='mainleft-content'>content is visible</div> <div id="expand-hidden">Button Expand +</div> To show/hide the divs, I am using JQuery as shown below: $(document).ready(function () { ...

Interactive chat feature with live updates utilizing jQuery's $.Ajax feature for desktop users

I came across a script for real-time chat using $.ajax jQuery, but it only refreshes my messages. Here's an example scenario: I type: Hello to You, and I see this message refreshed. You reply: Hey, in order to see your message, I have to manually refr ...