Getting the JSON representation of base64 data from a list of files

After retrieving a file list, I aim to transform it into a JSON array similar to:

[
  {"name":"IDCard001.jpg","base64":"data:image/jpeg;base64,/9j/4AA.."},
  {"name":"IDCard002.jpg","base64":"data:image/jpeg;base64,/9j/4AA.."},
]

This is the code I have written for this purpose:

  const getBase64 = (file: File) => {
    return new Promise((resolve, reject) => {
      let reader = new FileReader();
      reader.onload = () => resolve(reader.result as string);
      reader.onerror = (error) => reject(error);
      reader.readAsDataURL(file);
    });
  };

  const handleFiles = (files: Array<File>) => {
    const list = files.map(async (file) => {
      return {
        name: file.name,
        base64: await getBase64(file),
      };
    });
  }

I am facing an issue where I cannot use 'list' as a simple array. How should I proceed?

Answer №1

When using the map() method, the function's return value is crucial for proper functionality. Check out more information about the map() method on MDN.

If the variable list is storing Promises instead of the expected object, you need to surround the map function with await Promise.all(). Learn more about this process by reading about Promise.all() on MDN, and remember to make the function async in order to get the objects array.

const handleFiles = async (files: Array<File>) => {
  const list = await Promise.all(files.map(async (file) => {
    return {
      name: file.name,
      base64: await getBase64(file),
    };
  }));
  return list;
}

Answer №2

It can be challenging to pinpoint the exact cause, but it appears that your issue stems from executing asynchronous tasks within a map function without ensuring that all promises are resolved. To address this problem, you may consider resolving the promises as shown below.

const processFiles = async(files: Array<File>) => {
  const fileList = await Promise.all(files.map(async (file) => {
    return {
      name: file.name,
      base64Data: await getBase64EncodedString(file),
    };
  }))
  console.log(fileList)
}

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

Customizing error messages in Joi validationorHow to show custom

Hi there, currently I am utilizing "@hapi/joi": "^15.1.1". Unfortunately, at this moment I am unable to upgrade to the most recent Joi version. This represents my validation schema const schema = { name: Joi.string() .all ...

Tips on stopping the display of the search input name

I am a beginner and still getting the hang of things. The code below is functioning correctly, but I'm unsure how to hide the search input name from appearing on the page. Please see the image attached below as well. Thank you for your assistance in a ...

In VUE, switching colors upon clicking is undone once the cursor moves away from the element

I need help with changing the color of a div when it is clicked. Here's how the div is structured: <li v-for="monomer in monomers"> <div :style="monomerButton" @mouseover="hover = true" @mouseleave="hov ...

Isotope - How to Load Multiple Containers on a Single Page

My goal is to implement an isotope layout for multiple containers on a single page, with each container having the same ID. I am using Isotope version 2.1.0 which can be found at . The issue I am facing is that while Isotope works perfectly for the first ...

The functionality of NodeJs's String.includes() function may not meet the expected outcome

I am encountering an issue where I am unable to properly filter my list because the name.includes(line) is always evaluating to false. http .createServer((req, res) => { // .. Here you can create your data response in a JSON format let body = ...

What is the best way to incorporate this in a callback function?

Utilizing a third-party component requires creating an object for configuration, such as itemMovementOptions in the given code sample. export class AppComponent implements OnInit { readonly itemMovementOptions = { threshold: { horizontal: ...

Having trouble getting the equirectangular panorama example from Three.js to work on your device even though WebGL is supported?

After examining the WebGL equirectangular panorama example, it performs well on both desktop and mobile devices (such as the Samsung S4 Android 4.4.2) using the latest version of mobile Chrome. However, when tested on the Samsung tablet SM-T230 also runni ...

Unlocking the power of translation in React: Implementing Amazon Translate or Google Translate for AXIOS responses

I'm currently working on converting Axios JSON responses in React. Here is the code snippet: axios.get('https://jsonplaceholder.typicode.com/users') .then(res => { ...translation_logic_here setU ...

Speedily deliver a message to the designated destination

I have a specific route set up at /test: app.route('/test', (req,res)=>{ res.sendFile(__dirname + "\\myhtml.html") }) Now, I want to trigger an event in Node.js on the /test route, and have myhtml.html file listen for ...

Nested Promises in Angular's $q Library

I'm facing an issue with a function that should return a list of favorite locations. Here's the code snippet in question: When I call LocationsFactory.getFavoriteLocations(), it returns a promise like this: getFavoriteLocations: function() { ...

Finding the offsetWidth (or similar measurement) for a list item (LI) element

Can jQuery be used to determine the width of an element? alert($("#theList li:eq(0)").offsetWidth); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ol id="theList"> <li>The quick brown ...

What could be triggering the "slice is not defined" error in this TypeScript and Vue 3 application?

I have been developing a Single Page Application using Vue 3, TypeScript, and the The Movie Database (TMDB) API. In my src\components\MovieDetails.vue file, I have implemented the following: <template> <div class="row"> ...

I can't figure out why my unslider isn't adapting to the screen size. Check out the fiddle for more details

I recently implemented unslider to create a slideshow that spans 100% of the width on my website. Everything seemed to be working fine until I tried resizing the screen, and the slides remained the same size as they were initially loaded. Here is the code ...

Is there a way to capture and monitor all page traffic within a scrollable website using playwright?

Here is the code I am using: import { firefox } from 'playwright'; // domain let domain = 'https://www.reddit.com/' // create a new page const page = await browser.newPage(); // set routes await page.route('**', async route = ...

Using Three.js to display multiple objects simultaneously causes my browser to crash

When it comes to rendering objects in a scene, I encountered an issue with loading multiple objects. Initially, loading all 3 objects as STL files worked fine. However, when I attempted to divide each object into multiple surfaces and create BufferGeometry ...

Using useRef with setInterval/clearInterval in React with TypeScript

In my code, I am implementing a useRef object to store a NodeJS.Timeout component, which is the return type of setInterval(). However, when I attempt to use clearInterval later on, I encounter an error (shown below) on both instances of intervalRef.current ...

Sending Emails with AngularJS

Exploring AngularJs has been a delightful experience for me, and I recently stumbled upon a fantastic plugin for Angular called angular-http-auth. This plugin allows you to seamlessly integrate an identification system. Does anyone know of a similar resou ...

What is the best way to manage various versions of JS libraries across different branches?

As a novice developer, I dabble in creating applications for personal use. My go-to tools are the Quasar framework for the front end and Python for the back end. I maintain a git repository where the master branch houses my "production code," but now I am ...

Utilizing pixel values for Material-UI breakpoints rather than using the default sm, md, lg, xl options

Below is the code snippet that I am using: [theme.breakpoints.only('lg')]: {} The above code works perfectly and shifts at the desired breakpoint. However, when I implement the following: [theme.breakpoints.between('1200', '1021&a ...

Guide on incorporating jQuery into a jQuery plugin within an Angular 2+ application using Webpack or Angular CLI

I'm running into an issue importing a jQuery plugin into a single Angular component. It works fine in most browsers, but IE 11 is giving me this error: SCRIPT1002: Syntax error main.bundle.js (1376,1) When I investigate the error, it points me to th ...