Get the base64 encoding of a File object by utilizing the FileReader.readAsDataURL() method

Currently, I am facing an issue with converting a JS File object into a base64 value and returning that value within a JSON object. My approach involves using FileReader.readAsDataURL(), however, due to the asynchronous nature of this process, it appears that I am not obtaining the base64 value 'on time'. This results in the obj.data value being undefined when I call the callback function.

function mapFileData(file, callback) {
    var obj = {};
        obj.name = file.filename;
        obj.size = file.fileSize;
        obj.type = file.fileType;
        obj.data = getBase64(file);
    });

    console.log(JSON.stringify(obj)); // file object with undefined 'data' value 
    callback(obj);
}

function getBase64(file) {
    var fileReader = new FileReader();
    if (file) {
        fileReader.readAsDataURL(file);
    }
    fileReader.onload = function(event) {
        return event.target.result;
    };
}

I am unsure how to resolve the issue of making the obj.data value available when I invoke callback(obj). Any suggestions or guidance would be greatly appreciated!

Answer №1

To implement the conversion of a file to base64, it is recommended to switch from using callback syntax to utilizing async/await syntax.

Here's an example:

async function mapFileData(file) {
    var obj = {};
     const base64 = await getBase64(file);
        obj.name = file.filename;
        obj.size = file.fileSize;
        obj.type = file.fileType;
        obj.data = base64
        

    console.log(JSON.stringify(obj)); 
    return obj; // Instead of using a callback, consider returning the object and await this function in the caller
}

function getBase64(file) {
    var fileReader = new FileReader();
    if (file) {
        fileReader.readAsDataURL(file);
    }
    return new Promise((resolve, reject) => {
      fileReader.onload = function(event) {
        resolve(event.target.result);
      };
    })
}

Furthermore, it is advisable to convert the mapFileData function to async/await syntax, eliminating the need for callback usage.

UPDATE Below is the alternative solution with Callback syntax:

function mapFileData(file, callback) {
    
     const base64Callback = function(res) {
        var obj = {};
        obj.name = file.filename;
        obj.size = file.fileSize;
        obj.type = file.fileType;
        obj.data = res
        console.log(JSON.stringify(obj)); 
        callback(obj);
     }
     getBase64(file, base64Callback)
}

function getBase64(file, callback) {
    var fileReader = new FileReader();
    if (file) {
      fileReader.readAsDataURL(file);
    }
    fileReader.onload = function(event) {
      callback(event.target.result);
    };
}

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

What is the best method of transferring all procedures from frida javascript rpc.exports to python?

I have a JavaScript file containing rpc.exports rpc.exports = { callfunctionsecret: callSecretFun, callfunctionsomethingelse: callSomethingElse, } I am trying to retrieve a list of all these functions in Python, but I have been unable to find a so ...

Mapping JSON data from Mongoose to Vue and Quasar: A comprehensive guide

I have set up a Mongoose backend and created some REST APIs to serve data to my Vue/Quasar frontend. The setup is pretty basic at the moment, utilizing Node/Express http for API calls without Axios or similar tools yet. I have successfully implemented simp ...

What is the process for animating classes instead of ids in CSS?

My webpage currently features a setup similar to this. function wiggle(){ var parent = document.getElementById("wiggle"); var string = parent.innerHTML; parent.innerHTML = ""; string.split(""); var i = 0, length = string.length; for (i; i ...

Creating a classification for a higher order function

In the code snippet below, I have a controller that acts as a higher order method: const CourseController = { createCourse: ({ CourseService }) => async (httpRequest) => { const course = await CourseService.doCreateCourse(httpRequest. ...

How to manage print preview feature in Firefox with the help of Selenium in the Robot Framework

Attempting to select the 'cancel' button in the print preview page on Firefox has proven to be a challenge. Despite my efforts, I am unable to access the element by right-clicking on the cancel option. Interestingly, Chrome allowed me to inspect ...

How is it possible for JavaScript functions to be accessed prior to being defined?

Similar Question: Why can I access a function before it's declared in JavaScript? Unexpectedly, the following code results in an error due to the undefined Foo: window.Foo = Foo; This code snippet also triggers the same error: window.Foo = Foo ...

An issue has occurred: The necessary parameter (Slug) was not included as a string in the getStaticPaths function for the /post/[Slug] route

Hello, I've recently embarked on a tutorial journey to create the ultimate Modern Blog App using React, GraphQL, NextJS, and Tailwind CSS. However, I encountered an error that's giving me some trouble specifically when trying to access a post. He ...

jQuery animation not executing as expected due to transition issues

I'm looking to create a cool effect where the previous quote disappears and a new one appears when I click on a button, all with a smooth transition effect. In my attempt below using jQuery .animate and opacity property, I'm struggling to make i ...

React Native animation encountered a rendering issue: Invalid transform scaleDisliked value: { "scaleDisliked": 1 }

While working on my react native app, I encountered an issue when trying to apply a transform:scale effect to an Animated.View component. I am using interpolate for this purpose, but unfortunately, I keep receiving the following error message: Render error ...

A problem arose during the process of mapping an array of objects in react - There was a parsing error: An unexpected token was encountered, expecting a comma (13:9) with eslint

I am currently working on mapping an array of objects containing data, but I am encountering an error that I am unable to identify in the code. Please disregard the console.logs as they are for my own reference. https://i.sstatic.net/vbpLX.png import Reac ...

Using Regex named groups in JavaScript's replace() method

Currently in my JS project, I am facing a challenge while trying to create an object using the code snippet below. My difficulty lies in extracting regex named groups using the replace function provided. var formatters = { 'p': 'padding& ...

Deleting an item using jQuery

In the Document Object Model (DOM), there is a button available to remove the parent element here: <i class="fa fa-times remove-product-compare" aria-hidden="true"></i> Here is an example of my DOM structure: <div class="col-lg-12 col-md- ...

What is the best way to automatically select a checkbox when using ng-repeat on page

I'm looking to automatically check an input checkbox when the page loads, and if it's checked, subtract its value from the total. How can I tackle this issue? Here's the HTML snippet: <p>{{vm.TOTAL VALUE}}</p> <tr ng-repeat= ...

Seeking assistance in optimizing my Javascript code for more efficient canvas rendering

I've created a script for generating random moving lines as a background element for my portfolio. While it runs smoothly on its own, I encounter frame drops when combining it with other CSS animations and effects, especially at the beginning (althoug ...

Filtering Data with MongoDB Queries

In my data filtering form, I have approximately 15 to 20 dropdown fields. These dropdown fields are meant to provide various options for filtering data. As shown in the image below (from the Zoopla App): https://i.sstatic.net/KOBcc.png The image displays ...

The functionality of React-router-dom protected routes seems to be malfunctioning

Understanding Protected Routes in React.js: While looking at the implementation of protected routes, you may notice that 'false' is being directly used in the if statement. However, even with this condition, the page is still accessible. Why doe ...

Tips on concealing and deactivating the fullscreen option in flowplayer

Could someone please assist me in resolving this issue? I've been attempting to hide the fullscreen button from the flowplayer, but so far, I haven't found a solution. Below is my JavaScript code: <script> $f("player", "flowplayer/flowpla ...

Navigate through FAQ items with sliders using Owl Carousel 2 - Easily switch between different chapters

Exploring the creation of a FAQ section with individual carousels for each item. My primary objective is for the carousel to transition to the next chapter when advancing beyond the last slide (backwards navigation would be a future enhancement). I'v ...

Colorful Paper Trail Logging

After stumbling upon a post on the internet, I discovered that Papertrail offers the ability to log using ANSI colors. This is particularly appealing to me as my node.js app generates numerous logs, and adding color helps me decipher the information during ...

Table order is requested, but the index fails to comply

I am facing an issue with sorting and deleting data from a JSON table. Even after sorting the columns, clicking "Delete" removes the wrong entry because the $index is not updated properly. Here is the JavaScript code I am using: $scope.friends = ...