Transform a base64 image into a blob format for transmission to the backend via a form

Is there a way to convert a base64 string image to a blob image in order to send it to the backend using a form?

I've tried some solutions like this one, but they didn't work for me.

function b64toBlob(b64Data, contentType='', sliceSize=512) {
  const byteCharacters = atob(b64Data);
  const byteArrays = [];

  for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
    const slice = byteCharacters.slice(offset, offset + sliceSize);

    const byteNumbers = new Array(slice.length);
    for (let i = 0; i < slice.length; i++) {
      byteNumbers[i] = slice.charCodeAt(i);
    }

    const byteArray = new Uint8Array(byteNumbers);
    byteArrays.push(byteArray);
  }

  const blob = new Blob(byteArrays, {type: contentType});
  return blob;
}

Answer №1

After some thorough cleaning, I was able to find a solution that looks something like this:

export default async function convertBase64ToBlob(dataUrl: string): Promise<Blob> {
    let image = new Image();
    return new Promise((resolve, reject) => {
        image.onload = () => {
            const canvas = document.createElement("canvas");
            canvas.width = image.width;
            canvas.height = image.height;
            const context = canvas.getContext("2d");
            context?.drawImage(image, 0, 0);
            canvas.toBlob(
                (blob: Blob | null) => {
                    if (blob) resolve(blob);
                    else reject;
                },
                "image/jpeg",
                1
            );
        };
        image.onerror = reject;
        image.src = dataUrl;
    });
}

}

Here's how you can use it:

const blobData = await convertBase64ToBlob(myBase64String);
const formData = new FormData();
formData.append("image", blobData);
const { responseData } = await APIService.post("someurl/image", formData);

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 sets npm install apart from manual installation?

I've been exploring requirejs recently. I'm trying to decide between installing it using npm install requirejs or manually downloading it from the website. Are there any differences between the two methods? Are there any advantages or disadvantag ...

Unable to use global modules in NestJS without importing them

Currently, I am in the process of integrating a global module into my nest.js project I have written a service as shown below: export interface ConfigData { DB_NAME: string; } @Injectable() export class ConfigManager { private static _inst ...

Activate JavaScript validation

Within each section (displayed as tabs), I have a custom validator. When one tab is active, the other is hidden. To proceed to submission, I need to disable client validation for the inactive tab. I attempt to do this by calling ValidatorEnable(, false); ...

The animation unexpectedly resets to 0 just before it begins

Currently, I am developing a coverflow image slider with jQuery animate. However, there are two issues that I am facing. Firstly, when the animation runs for the first time, it starts at `0` instead of `-500`. Secondly, after reaching the end and looping b ...

Setting the default selection in AngularJS based on the URL entered

I've encountered an issue with a dropdown menu in my AngularJS version 1.4 application. The dropdown menu contains links to different sections of the page. The problem arises when I directly enter the page URL - instead of selecting the correct link f ...

How can I protect my jQuery script from being accessed by "FIREBUG"?

I was tasked with creating a jQuery script as follows: function DeleteFile(_FileID) { //ajax method to delete the file } The FileID is stored in the 'rel' attribute of the list. However, when I call "DeleteFile" from Firebug using the fileId ...

The design problem arises from using jQuery to dynamically prepare the table body at runtime

The table row and data are not appearing in the correct format. Here is a link to the problem on Fiddle: http://jsfiddle.net/otc056L9/ Below is the HTML code: <table border="1" style="width: 100%" class="eventtable"> <thead style="color: b ...

loading dynamic content into an appended div in HTML using Angular

Here is the HTML code from my app.component.html file: <button mat-raised-button color="primary" mat-button class="nextButton" (click)="calculatePremium()"> Calculate </button> <div id="calcul ...

The (ReactJS + Redux) form fails to load when the /new segment is appended to the URL

I'm currently working on a project using React, Redux, and Rails. I've encountered an issue with loading the form. In my App.js file, I have set up a Router that defines the routes. import React, { Component } from 'react'; import { Br ...

Obtaining the response object for the web browser

Greetings! I currently have a function within router.js in NODEJS : const authenticateUser = (req, res, next) => { //something }; Whenever my application is live, this function is triggered. I am looking for a way to examine the response object. Is ...

Translating PCRE(PHP) regular expressions into ECMAScript(Javascript) syntax

I have this PCRE Regex that I'm using to validate JSON strings, but now I need to convert it to JavaScript so I can use it for validation in a React application. PCRE Regex - /(?(DEFINE) (?<json>(?>\s*(?&object)\s*|\s* ...

Angular firebase Error: The parameter 'result' is missing a specified type and is implicitly assigned the 'any' type

I have encountered an issue with the code I am working on and both the result and error are throwing errors: ERROR in src/app/login/phone/phone.component.ts(48,75): error TS7006: Parameter 'result' implicitly has an 'any' type. s ...

Learn how to implement autofocus for an ng-select element within a bootstrap modal

When working with ng-select inside a modal, I am facing an issue with setting autofocus. While I am able to add focus for the input field within the modal, the same approach doesn't work for ng-select. Can anyone provide guidance on how to set focus f ...

When using TypeScript and React with Babel, an error may occur: "ReferenceError: The variable 'regeneratorRuntime'

I've been delving into learning typescript, react, and babel, and here is the code I've come up with: export default function App(): JSX.Element { console.log('+++++ came inside App +++++++ '); const {state, dispatch} = useCont ...

`Next application will have all accordions simultaneously opening`

Is there a way to make the accordion open only one item at a time? Currently, when I click on one accordion item, all of them expand simultaneously. The data is being fetched from a local JavaScript file and consists of a list of objects with questions a ...

Is the npm mqtt module continuously running but not performing any tasks?

I'm relatively new to the world of JS, node.js, and npm. I am attempting to incorporate a mqtt broker into a project for one of my classes. To gain a better understanding of how it functions, I installed the mqtt module from npm. However, when I tried ...

What is the best way to modify the CSS of a child element within the context of "$(this)"

On my search results page, each result has an icon to add it to a group. The groups are listed in a hidden UL element on the page with display:none. The issue I'm facing is that when I click on the icon for one result, the UL appears under every sing ...

Is there a way to make the submit button navigate to the next tab, updating both the URL and the tab's content as well?

I am encountering an issue with my tabs for Step1 and Step2. After pressing the submit button in Step1, the URL updates but the component remains on tab1. How can I resolve this so that the user is directed to the Step2 tab once they click the submit butto ...

The functionality of Webdriver.waitUntil is not meeting the expected outcomes

I'm currently utilizing webdriverio version 4.5: ./node_modules/.bin/wdio -v v4.5.2 In my scenario, I am in need of waiting for the existence of a specific element and handling the situation if it doesn't exist. Here is an example code snippet ...

Include the component with the function getStaticProps loaded

I am currently working on a project using NextJs and I have created a component to load dynamic data. The component works fine when accessed via localhost:3000/faq, but I encounter an error when trying to import the same component into index.js. It seems l ...