transform an array encoded in base64 format into a JSON object

I am encountering an issue where the base64 array I'm trying to send to an API is coming up empty. Here's a breakdown of what I'm doing:

Firstly, I have an array of files with images in my code:

[0: File {name: '766_generated.jpg', lastModified: 1613057822000, lastModifiedDate: Thu Feb 11 2021 12:37:02 GMT-0300 (Horário Padrão de Brasília), webkitRelativePath: '', size: 191010, …}]

In my function, I iterate over the image array, convert each image into base64, and store it in another array like so:

let filesBody = []
this.files.map(item => {
        var reader = new FileReader();
        reader.readAsDataURL(item);
        reader.onload = function () {
          let result = reader.result
          return filesBody.push(result)
        };
      })

Upon console logging the filesBody array, I get the following result:

[0: "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAASABIAAD…AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAf/Z"]

The body object containing the filesBody array looks like this:

let body = { "files": filesBody }

After attempting to send the body through a POST request using the billing service:

this.billingService.sendBillingRevaluation(body)

The service function responsible for sending the data is as follows:

sendBillingRevaluation(body): Observable<any> {
    return this.http.post<any>(
      `${ServicesUrls.URL}/queries/sendBillingRevaluation`,
      body
    )
  }

However, upon inspection, the base64 array within the body object appears to be empty when sent:

{
    "files": []
}

Both the network tab in the browser and the backend endpoint log confirm that the base64 array is not being transmitted correctly. Is there another method I should consider for sending base64 data as JSON?

Answer №1

After researching the problem, I found a helpful solution on Stack Overflow related to converting an array of inputted files to base64 using FileReader. You can find the original question here: Convert array of inputted files to base64 using FileReader

Below is my final code implementation:

Promise.all(
        this.files.map(
          (image) =>
            new Promise((resolve, reject) => {
              const fileReader = new FileReader();

              fileReader.onload = (file) => {
                resolve(file.target.result);
              };

              fileReader.onerror = (error) => reject(error);

              fileReader.readAsDataURL(image);
            })
        )
      ).then((base64Images) => {
        let body = { "files": base64Images }

        this.billingService.sendBillingRevaluation(body)
          .toPromise()
          .then(res => {
            this.closeModal()
          })
          .catch(err => {
            this.states.error = true
          })
      });
    }

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

Using Angular 4 and Bootstrap to create a Modal Component

I am contemplating the idea of integrating a component into an application that can function both as a Bootstrap modal and as a regular child component within a page. In the example provided on the referenced link, a component being used in a modal requir ...

Simulating NestJS Injected Connection Imported from Another Module

Today, I've been facing this persistent error: Encountering an issue with the ClubsService where Nest is unable to resolve dependencies (specifically DatabaseConnection). The error message prompts me to ensure that the argument DatabaseConnection at i ...

Transforming a current angular 2 project to incorporate angular CLI

I was working on a project which wasn't set up using the 'ng new' command, but rather I followed the steps outlined in the quickstart guide. However, whenever I try to use an angular CLI command like 'ng generate', I keep getting t ...

What is the best method for connecting an Angular 2 application with an existing Angular JS app?

I recently created an application using Angular 2 and now I am looking to combine it with an Angular JS app. ...

Tips for preserving the status of radio buttons in a React application

I am currently utilizing a Map to keep track of the state of radio buttons, but I am facing challenges when it comes to correctly saving and updating it whenever a user makes a selection. The structure of my Map is as follows: { "Group A": [ ...

What is the best way to retrieve HTML content using an Angular method?

Okay, so the title might not be the greatest...but I couldn't think of anything better: I want to emphasize search keywords in the result list...that's why I'm having trouble with this problem. CSS: .highlightText{ font-weight: bold; } In ...

Compilation errors plague TSC on varying systems

After successfully creating a node app in TypeScript and running it locally without any issues, I encountered compilation errors when deploying the app on Heroku: app/api/controllers/ingredient.controller.ts(3,24): error TS2307: Cannot find module & ...

Dealing with routing problems within sub-routes using Angular 2 and Express, attempting to serve content from sub-folders

I am currently using Express to serve a local Angular2 application. To enable the Angular2 app to access various node_modules from Express, I have set up the following configuration: config.dependencies = [ { staticPath: './node_modules/@angular/&a ...

Error message indicating a problem with global typings in Angular 2 when using Webpack is displayed

My project is utilizing angular 2 with webpack and during the setup process, I encountered Duplicate identifier errors when running the webpack watcher: ERROR in [default] /angular/typings/globals/node/index.d.ts:370:8 Duplicate identifier 'unescape& ...

What is the reasoning behind TypeScript's decision to permit implicit downcasting in method parameters?

Consider the following example: interface Vehicle{ mass:number } interface InspectorClass{ inspect(v:Vehicle):void } class Car implements Vehicle{ mass = 2000 wheels = 4 } class Boat implements Vehicle{ mass = 3000 sails = 2 } ...

Encountering an error during ng build -prod with Angular 9, as the css-loader module cannot be located

My package.json configuration looks like this: "dependencies": { "@angular/common": "2.2.1", "@angular/compiler": "2.2.1", ... }, "devDependencies": { "@types/jasmine": "^2.2.30", "angular-cli": "1.0.0-beta.21", ... I was successfully running ng buil ...

The continuity of service value across parent and child components is not guaranteed

My goal is to update a value in a service from one component and retrieve it in another. The structure of my components is as follows: parent => child => grandchild When I modify the service value in the first child component, the parent receives t ...

Utilizing the validator in Vue with the setup script, TypeScript, and the composition API

While working on some code from a tutorial, I came across the challenge of implementing a validator in a similar fashion to the example provided. My task involves utilizing the script setup, typescript, and the composition API. props: { image: { ...

Obtaining the value of an identification number from one service using the identification number from another service

I am currently working on an angular application that retrieves job information, including the customer's name. When storing this data in the jobs table, I make sure to include the customerId within the JobModel. Within my angular job component, I in ...

Using prevState in setState is not allowed by TypeScript

Currently, I am tackling the complexities of learning TypeScipt and have hit a roadblock where TS is preventing me from progressing further. To give some context, I have defined my interfaces as follows: export interface Test { id: number; date: Date; ...

Tips for utilizing a function to assess ngClass conditional statement in Angular 2

So as I loop through my list using *ngFor, the code snippet is like this: [ngClass]="{'first':isStartDate(event,day)}" The function isStartDate is defined in my component. An error message appeared: "Unexpected token : " ...

What is the best way to retrieve the height and width of a device's display in Angular 2 using Typescript

I came across this code snippet. Do you think it's valid? import {Component} from '@angular/core'; import {Platform} from 'ionic-angular'; @Component({...}) export MyApp { constructor(platform: Platform) { platform.ready().then ...

Unusual Observable behavior in Angular/Typescript leaves developers scratching their heads

I have encountered an issue with a single Angular 2 service: validate() { return this.http.get('api/validate', data); } Consuming the API works fine: this.ValidationService.validate().subscribe(result => { console.log(&a ...

The HttpClient.get('/') request with {observe: 'response'} is failing to retrieve some headers

Currently, I'm in the process of writing an API GET request by utilizing HttpClient.get(). Upon passing in the option to observe the response, I've encountered an issue where accessing the .keys() does not provide me with any headers apart from C ...

Ways to conduct testing on React Native Typescript app COMPONENTS using jest

I've been struggling to set up testing for my React Native Typescript Components using Jest. Despite searching through various examples and solutions (such as this one, that one, another link, etc.), I still can't seem to get it working. Even fol ...