What is the best way to retrieve the Base64 string from a FileReader in NextJs using typescript?

My goal is to extract a string from an object I am receiving in the response.

const convertFileToBase64 = (file: File): Promise<string> => {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file); // Read as Data URL (includes Base64 encoding)
        reader.onload = () => {
            const base64 = (reader.result as string).split(',')[1];
            resolve(base64);
        };
        reader.onerror = error => reject(error);
    });
};

https://i.sstatic.net/MxZD6.png

Even after using split, I'm still getting the object instead of the desired string:

reader.onload = () => {
    const base64 = (reader.result as string).split(',')[1];
    resolve(base64);
};

Answer №1

I successfully retrieved the text, and this is how I accomplished it:

if (values.institution_recommendations.attachment) {
    const fileReader = new FileReader();
    fileReader.onload = () => {
        values.institution_recommendations.attachment = (fileReader.result as string).split(',')[1];
    };
    fileReader.readAsDataURL(values.institution_recommendations.attachment);     
}

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

The compiler error TS2304 is indicating that it cannot locate the declaration for the term 'OnInit'

I successfully completed the Angular superhero tutorial and everything was functioning properly. However, when I close the CMD window running NPM and then reopen a new CMD window to reissue the NPM START command, I encounter two errors: src/app/DashBoard ...

Fixed-sized array containing union parameters

One of my programming utilities allows me to create a statically sized array: export type StaticArray<T, L extends number, R extends any[] = []> = R extends { length: L; } ? R : StaticArray<T, L, [...R, T]>; To verify its functionality, ...

What is the best way to find a partial string match within an array of objects when using Jest?

I am currently utilizing the following versions: Node.js: 9.8.0 Jest: 22.4.2 A function called myFunction is returning an array structured like this: [ ... { id: 00000000, path: "www.someUrl.com/some/path/to" } ... ] I ...

What is the relationship between Firefox bookmark tags and the corresponding bookmark?

I am looking to modify my Firefox bookmarks by exporting them to a .json file and importing them into my program. As I analyze the file, I come across a bookmark entry that contains random strings which make it easier to locate within the JSON data: The b ...

Enhancing the Value of BehaviorSubject with Object Assign in Angular using Typescript and RxJs

I have a user object stored as a BehaviorSubject which is being observed. I need help figuring out how to detect if a specific value within my user object has changed. I've noticed that my current implementation doesn't seem to work correctly, a ...

Ways to view the outcome of json_encode function?

In PHP, I have an array that looks like this: $user_data = Array ( [session_id] => 30a6cf574ebbdb11154ff134f6ccf4ea [ip_address] => 127.0.0.1 [user_agent] => Mozilla/5.0 (Windows NT 5.1; rv:9.0.1) Gecko/20100101 Firefox/9.0.1 [las ...

Property ngIf in Angular is not being supplied by any relevant directive within the embedded template

When attempting to use ngIf, I encountered an error with a red underline. The error message states: "Property ngIf is not provided by any applicable directive on an embedded template." I then attempted to import commonModel, but received a new error: "src ...

How can I rectify the issue in TypeScript where the error "not all code paths return a value" occurs?

While developing an application, I encountered an error that says: "not all code paths return a value". The error is specifically in the function named addValues, indicating that the function must return "Obj[] | undefined". Here is the code snippet in qu ...

How to Use a For Each Loop with Google Maps DrawingManager to Create Polygons?

My Ionic 4 Application using Angular 8 incorporates a google maps component where I need to draw and edit multiple polygons, eventually saving their vertices in a database. Hard coding some polygons is easy with getPath() or getPaths(), but I'm utiliz ...

What is the best way to update the value of a variable within a specific child component that is displayed using ngFor?

Hello there, I'm in need of some assistance with a coding issue. I have a parent component named "users-list" that displays a list of child components called "user" using *ngFor. Each component's class is dynamic and depends on various internal v ...

Establish Database Table and Populate it with Entries from a JSON File

Currently, I am facing three main challenges. Firstly, I have a JSON file with approximately one million records. My goal is to create a database from this file, but the issue lies in the fact that the JSON is multi-level. Since I am inexperienced in this ...

Refresh inherent properties in Opscode Chef (serialized_object)

There was a slight hiccup with a few nodes on my chef server during the bootstrapping process. Unfortunately, they missed capturing the FQDN and domain automatic attributes which caused them to not be indexed by SOLR and therefore not searchable by knife ...

What causes TypeScript to automatically infer a default property when dynamically importing a JavaScript file that lacks a default export?

While dynamically importing a javascript file that exports multiple functions (without a default export), I encountered this issue: const sayHi = import('./sayHi.js') I was expecting the type of sayHi to be Promise<{name1: function, name2: fu ...

The selection of activities is made dynamically while the splash screen is being

Today, as I was working on a small project, we decided to add conditional validation in the splash screen. The project was almost complete when this decision was made. I made some modifications to my class and everything seemed fine until I added a timeou ...

Adding identifiers to columns in DataTables depending on the value of another attribute

I am facing a challenge with inserting the <span> tag into the "salesStatusName" column cell that already contains some data. This should only happen when the value of the last column, "completelyDelivered", is true. However, I do not want to display ...

Accessing files from various directories within my project

I'm working on a project with 2 sources and I need to import a file from MyProject into nest-project-payment. Can you please guide me on how to do this? Here is the current file structure of my project: https://i.stack.imgur.com/KGKnp.png I attempt ...

What is the best way to choose a specific JSON element?

Seeking information from an API, my goal is to extract specific data using JavaScript selectors. I am specifically interested in two objects from the JSON below: [ { "symbol": { "tickerSymbol": "@CH20", "vendor": "DTN", "marketName ...

The Vue component mistakenly saves the image to the incorrect location when the file @change event is triggered

I've encountered an issue with my image slider component. Users have the option to add an extra image to the end of the slider, but when there are multiple instances of the same slider component on a page, it always adds the image to the first compone ...

I'm puzzled by the error message "Unhandled Exception: type 'double' does not match type 'int'" that keeps popping up as I try to parse JSON data in my Flutter application. What could be causing this issue?

I am trying to create a banner list in my app using YouTube thumbnails. I encountered an exception while parsing the JSON data: "Unhandled Exception: type 'double' is not a subtype of type 'int'". Here's a brief overview of what I ...

Discovering the functionality of es6 object.assign and find methods within a typescript file

Currently, I am in the process of transitioning from Java Script to TypeScript for my project. However, I am facing limitations as I am unable to utilize object.assign() and find methods. ...