Converting Blob to Base64 using javascript

I've managed to successfully convert my base64 (DATA_URI) image into a blob, but I'm facing issues with reverting it back.

Here's what my base64 to blob code looks like for better understanding. Check out this link.

b64toBlob(b64Data, contentType, sliceSize) {
    contentType = contentType || '';
    sliceSize = sliceSize || 512;

    var byteCharacters = atob(b64Data);
    var byteArrays = [];

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

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

        var byteArray = new Uint8Array(byteNumbers);

        byteArrays.push(byteArray);
    }

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

However, when I try to convert my blob back to base64, I encounter an error:

ERROR TypeError: Failed to execute 'readAsDataURL' on 'FileReader': parameter 1 is not of type 'Blob'.

For the response related to getting my blob image back, check https://i.stack.imgur.com/UlPCW.png.

Despite invoking the success callback, I'm struggling to comprehend the issue at hand.

The following is the code snippet where I attempt to convert blob to base64:

if(window.FileReader) {
          var reader = new FileReader();
          reader.readAsDataURL(blob); 
          reader.onloadend = () => {
              var base64data = reader.result;                
              console.log(base64data);
          }
        }

During debugging, I notice that reader.onloadend appears to be null, preventing me from calling it. Any suggestions?

Answer №1

In order to ensure that the onloadend is properly defined and executed, you should set it up before attempting to read the data. This will prevent the function from firing prematurely or being null when called. Specifically, make sure that at the moment of invoking readAsDataURL, onloadend is indeed a valid function.

var reader = new FileReader();
reader.onloadend = () => {
  var base64data = reader.result;                
      console.log(base64data);
}

reader.readAsDataURL(blob); 

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

Getting a specific index from an array using the Angular ng-repeat Directive: A step-by-step guide

I am trying to retrieve a specific index in an array using the ng-repeat directive. Currently, it is displaying information for all indexes... I only want to display the information for the second index as an example... This is my main.js: app.controll ...

Making HTTP requests with axios in Node.js based on multiple conditions

I'm facing an issue with making get calls using axios to both activeURl and inactiveURl. The goal is to handle error messages from the activeUrl call by checking data from the inactiveUrl. However, I keep receiving error messages for the inactiveURL e ...

Is it possible to create a personalized serialize form when sending an AJAX POST request

How can I format form data on an AJAX POST request differently than the default $("#formid").serialze()? The current result is not suitable for my needs, as it looks like this: `poststring="csrfmiddlewaretoken=bb9SOkN756QSgTbdJYDTvIz7KYtAdZ4A&colname= ...

Can the break statement be used in jQuery or JavaScript?

I created a function that picks a text based on the input string. If there is a match, it sets it as selected. Here is the function: function chooseDropdownText(dropdownId,selectedValue,hfId){ $('#'+dropdownId+' option').ea ...

Executing PHP Functions with Script Tags

I am trying to use PHP to output the <script></script> tag. Here is the code I am using: <?php echo "test"; echo "<br>"; echo '<script src="http://mywwebiste./mycode.js" type="text/javascript& ...

Listening to events on the iterative variable of NgFor directive in Angular 2

Angular2 has been my latest exploration in solving a unique data binding challenge. In my UI, I've presented a javascript array of objects like a database recordset in an HTML table. Each row contains menus and inputs allowing users to modify the rec ...

Developing an HTML table with the power of JavaScript and JSON

I am having difficulty creating an HTML table using JavaScript with JSON input. In my code, I'm using a placeholder in the HTML that will be filled by a innerHTML call in Javascript: for (var i = 0; i < json.data.length; i++) { listItem = json. ...

Improving efficiency for handling a vast number of inputs in React applications

Dealing specifically with Material UI, I am faced with the challenge of rendering a large number of inputs (more than 100) while effectively managing global state. Performance issues arise when using the Material UI <TextField /> component, with noti ...

Handlers for adjustments not correctly updating values in introduced object

I am facing an issue with a table that displays data fetched from an API and a select dropdown. Whenever a checkbox is selected, the name key along with its value is added to an array object named selectedFields. checkbox = ({ name, isChecked }) => { ...

Display different divs based on the number of clicks with the help of ng-show, ng-click, and ng-init

I am looking to display one div by default. Upon clicking a button, I want to show the second div and then upon another click, show the third div. I have experimented with ng-if and ng-show without success. <table class=""> &l ...

Populate a table with data from a different table using JavaScript

On my webpage, I have a grid of selectable divs that are defined by rows and columns. When I select certain divs, it creates what I'll call "table Copy", a three-dimensional table. If I select different elements, another three-dimensional table calle ...

JS faces a challenge when it comes to functional programming

Experimenting with bind, call, and apply, I am exploring updating object properties by passing function return values to object methods. This updating is triggered by the window resize event. var el = document.getElementById('someElement'); ...

Modifying the image height in a column using Bootstrap and JSON data

My webpage is dynamically generating images from a JSON file through a JavaScript file. However, the images are displaying at different heights, and I want each column to adjust to the height of the image to eliminate any gaps. Particularly, data with the ...

I encountered an Angular error that is preventing me from updating and uploading images to my Firebase Storage because it is unable to locate the storage bucket

Hey there fellow developers! I'm currently working on a simple Angular app that allows users to upload images to a gallery. However, I've encountered an issue while trying to upload the images to Firebase Storage. I keep getting an error mentioni ...

Please explain this ES6 syntax to me: Using a colon after a function call

While exploring the documentation for a flux store in React, I came across an example that caught my attention. import {ReduceStore} from 'flux/utils'; class CounterStore extends ReduceStore<number> { getInitialState(): number { ret ...

Load a webpage with two dropdown menus in JavaScript/jQuery that have the same selection option pre-selected

I am facing an issue with two dropdown menus that should display the same value when the page loads. These dropdowns are used for filtering products on a WooCommerce website based on the selected vehicle. Initially, the user selects the Make, Model, and Se ...

Finding the identification of the first element within a nested div using JQuery

Here is the HTML snippet that I am working with: <div id="parent"> <div id="computer"> <div id="items"> <div id="1">hp</div> <div id="2">compaq</div> <div id="3"& ...

Encountering a 404 Not Found issue while trying to add scripts with Node.js

I am currently working with a node server and an HTML file, where the default route is being directed. server.js /** * Created by Creative Coder on 10/26/2015. */ var express = require('express'); var mysql = require('mysql'); var a ...

Unable to locate the module name loaded using require() function

Within my React file, I am importing a Javascript file like this (I am using Typescript): let FloDialog = require('../public/js/flo-dialog.min'); Afterwards, I declare a property for the dialog class: dialog: FloDialog = null; It is important ...

Ways to trigger an event or invoke a function after initializing Stripe JS

My checkout page is optimized with the new Stripe Payment Element for fast loading using SSR. However, I am facing an issue where the element sometimes causes the page to reload 2 or more times before functioning properly. Occasionally, it also displays ...