Converting blobs to strings and vice versa in Javascript

After successfully converting a blob to a string using FileReader, the challenge now is to convert it back:

var reader = new window.FileReader();
reader.readAsDataURL(blob);
reader.onloadend = function() {
   base64data = reader.result;
   var blobToSend = base64data.substr(base64data.indexOf(',')+1);
   rtcMultiConnection.send({"command":{
       "recording":blobToSend,
       "type":blob.type,
       "size":blob.size
   }});
}

The above code snippet is used in conjunction with https://github.com/muaz-khan/RTCMultiConnection. However, the main inquiry remains on how to reconstruct the blob after it has been sent. It appears that sending the blob as-is did not produce the desired results.

Answer №1

source: Creating a Blob from a base64 string in JavaScript This function is a reliable way to convert base64 data back to its original binary form. To enhance performance, the data is processed in blocks of the specified sliceSize. Please note that the source code is written in TypeScript.

    public static Base64ToBlob(b64Data, contentType = "", sliceSize = 512): Blob
    {
        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;
    }

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

Trouble accessing setState within an axios call in ReactJs

I've encountered an issue while attempting to set the state of the variable isCorrectAnswer within an axios call. The error message Cannot read properties of undefined (reading 'setState') is showing up in the console log. What mistake am I ...

Error: The function initMap() is not recognized in the Google Maps API

I have been experimenting with the Flickr API and I'm currently working on asynchronously loading images along with their metadata. To accomplish this, I have a script that utilizes three AJAX calls: $(document).ready(function() { var latLon = { ...

Creating an interactive dropdown feature using AngularJS or Ionic framework

$scope.AllCities = window.localStorage.getItem['all_cities']; <div class="row"> <div class="col"> <div class="select-child" ng-options="citie.name for citie in AllCities" ng-model="data.city"> <label&g ...

Creating a reverse proxy using next.js

My goal is to set up a reverse proxy for the GeForce NOW website using Next.js, but I'm struggling to make it work. module.exports = { async rewrites() { return [ { source: '/:slug', destination: 'https://pla ...

Creating methods in Vue that can alter elements created during the mounted lifecycle hook can be achieved by defining functions

I am trying to implement a button that can recenter the canvas. The idea is that when the button is clicked, it will trigger the rec() method which should reposition the canvas that was created in the mounted() function. However, this setup is not working ...

"When the value is false, use the Vue binding to apply a specific

My challenge involves managing a website that is designed to receive boolean values and store them in an array where the key represents the ID and the value represents the boolean. For example: policiesActive[ "2" => false, "3" => false] The w ...

Is there a way to retrieve JSON data using Vue and Axios?

I'm facing an issue trying to retrieve product data from a JSON file. Despite attempting different methods and searching for solutions online, I have not been able to find one that fits my specific scenario. As I am new to both Vue and axios, I apprec ...

What are some effective techniques to optimize this node.js code and eliminate redundancy?

I am currently in the process of setting up a basic template for my demonstration project and writing my first node.js program. The piece of code below is functioning properly for my initial test, but it contains duplicated sections - Getting connection, E ...

Upon calling the createModalAddPost() function, a single window is triggered to open

Hey there, I'm having a JavaScript question. So, I have a panel that opens a window, and it works fine. But the issue arises when I close the window and try to open it again - it doesn't work. I have to reload the page every time in order to open ...

Protractor: Unable to reach variables within closure set in the parent function

I have a code snippet in one of my JS files that looks like this: // test/lib/UserHelper.js 'use strict'; var Firebase = require('firebase'); exports.createUser = function (email, password) { browser.executeAsyncScript(function (do ...

Issues with basic emit and listener in socket.io

I recently inherited an App that already has socket IO functioning for various events. The App is a game where pieces are moved on a board and moves are recorded using notation. My task is to work on the notation feature. However, I am facing issues while ...

What benefits does React offer that jQuery does not already provide?

What sets ReactJS apart from jQuery? If jQuery can already handle everything, why should we use React? I've tried to research on Google but still don't have a clear answer. Most explanations focus on terms like "views," "components," and "state" ...

Converting a base64 string to a PNG format for uploading to an S3 bucket from the frontend

Feeling a bit overwhelmed here, hoping this isn't just a repeat issue. I've come across similar problems but none of the solutions seem to be working for me at the moment. I'm currently utilizing react-signature-canvas for allowing users to ...

Identify a CSS style or attribute that is being dynamically assigned using JavaScript

While using the Jquery Cycle plugin for my slideshow, I'm looking to trigger an event when a specific slide is active. The Cycle plugin handles this by adjusting the opacity of images within a div in this manner: <div style="position: absolute; to ...

Adding npm packages to your Vue.js application

My Vue app is structured like this (auto created by vue init webpack myProject): index.html components/ -main.js -App.vue I am trying to include npm packages, such as https://github.com/ACollectionOfAtoms/atomic-bohr-model. Following the instructions, I ...

Load various types of classes and run functions with matching names

I have encountered a challenging issue that needs to be resolved. Imagine having multiple classes located in a directory named services. These classes all include a constructor() and send() method. Examples of such classes can be Discord, Slack, SMS, etc. ...

JavaScript: How to identify and select a specific item from a context menu

Currently diving into the world of JavaScript, so please keep that in mind when explaining. My main goal is to figure out a way to detect when a user triggers a right-click or uses the context menu from the keyboard. Specifically, I want to know if they s ...

Cast your vote once for each post within the Angular application

Currently, users are only able to vote up or down once in general. I would like to allow users to vote up or down once per post. <div ng-repeat="post in posts | orderBy:'-upvotes'"> <span class="glyphicon glyphicon-thumbs-up" ...

The integration of a side panel with a chrome extension is experiencing issues

I am working on a chrome extension with the following functionalities - Extract URL path from a specific webpage. (The webpage's URL remains constant) Open this URL in a new tab. It can be either http:// or https://. Embed an iframe containing a sim ...

The offset value was inconsistent in the desktop version of Firefox

Could you take a look at my code on the fiddle link, Here is the code snippet: <body> <div id="content" style="width:400px; height:110px;"> <svg id="circle" height="300" width="300"> <circle cx="150" cy="150" r="40" st ...