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

Form the docs readAsDataURL encodes to base64

As an awaitable function:

function blobToBase64(blob) {
  return new Promise((resolve, _) => {
    const reader = new FileReader();
    reader.onloadend = () => resolve(reader.result);
    reader.readAsDataURL(blob);
  });
}

Note: The blob's result cannot be directly decoded as Base64 without first removing the Data-URL declaration preceding the Base64-encoded data. To retrieve only the Base64 encoded string, first remove data:/;base64, from the result.

Answer from Arun Killu on Stack Overflow
🌐
Stack Overflow
stackoverflow.com › questions › 68368840 › how-to-convert-blob-image-to-base64-base64-variable-showing-up-as-null
angular - how to convert blob image to base64? base64 variable showing up as null - Stack Overflow
July 13, 2021 - onDownloadImage(): void { this.progress = 0; this.download(this.imageUrl, {}).subscribe((event: any) => { if (event.type === HttpEventType.DownloadProgress) { this.progress = Math.round((100 * event.loaded) / event.total); console.log('progress', event.loaded); } else if (event instanceof HttpResponse) { this.processReceivedBlob(event.body); } }); } ... private processReceivedBlob(blob: any) { var reader = new FileReader(); reader.onload = () => { const dataUrl: any = reader.result; const base64 = dataUrl.split(',')[1]; this.img.src = 'data:image/png;base64, ' + base64; }; reader.readAsDataURL(blob); }
🌐
GitHub
gist.github.com › n1ru4l › dc99062577b746e0783410b1298ab897
Fetch blob and convert to base64 · GitHub
Fetch blob and convert to base64 · Raw · index.js · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
🌐
Stack Overflow
stackoverflow.com › questions › 64348624 › angular2-convert-blob-to-long-base64
angular - Angular2 - Convert Blob to long base64 - Stack Overflow
var blob = new Blob([response], {type : "image/jpg"}), reader = new FileReader(); reader.readAsDataURL(blob); reader.onloadend = function() { console.log(reader.result); }; ... description: "URL [file:20201014_0822_05020362.jpg]" file: ...
🌐
StackBlitz
stackblitz.com › edit › blob-base64-dataurl
Blob Base64 Dataurl - StackBlitz
Starter project for Angular apps that exports to the Angular CLI
🌐
JSFiddle
jsfiddle.net › wilt › 1u9fgyh0
From blob to base64 string - JSFiddle - Code Playground
JSFiddle - Test your JavaScript, CSS, HTML or CoffeeScript online with JSFiddle.
🌐
StackBlitz
stackblitz.com › edit › read-image-from-url-and-convert-it-in-base-64
Read Image From Url And Convert It In Base 64 - StackBlitz
name = 'Angular'; constructor(private http: HttpClient) { } ngOnInit() { this.http.get('https://avatars0.githubusercontent.com/u/5053266?s=460& v=4', { responseType: 'blob' }) .pipe( switchMap(blob => this.convertBlobToBase64(blob)) ) .subscribe(base64ImageUrl => console.log(base64ImageUrl)); } convertBlobToBase64(blob: Blob) { return Observable.create(observer => { const reader = new FileReader(); const binaryString = reader.readAsDataURL(blob); reader.onload = (event: any) => { console.log('Image in Base64: ', event.target.result); observer.next(event.target.result); observer.complete(); }; reader.onerror = (event: any) => { console.log("File could not be read: " + event.target.error.code); observer.next(event.target.error.code); observer.complete(); }; }); } } Enter to Rename, Shift+Enter to Preview ·
🌐
Medium
abhayahire.medium.com › angular-view-blob-base64-image-and-print-pdf-33b8e7dfaecd
Angular View Blob (Base64) Image and Print PDF | by Abhay Ahire | Medium
August 14, 2022 - Let’s generate angular application from scratch Use ng new print-pdfcommand to create new angular project. Now as first thing we need to show image into browser. We have added static base64 encoded string into assets folder within data.json file. You can check github link to see the contents.
Find elsewhere
🌐
Base64.Guru
base64.guru › home › developers › javascript › examples
Encode Blob to Base64 in JavaScript | Examples | JavaScript | Developers | Base64
Another way to convert Blob to Base64 is to call reader.readAsBinaryString(blob) and use btoa(reader.result) to get the Base64 string.
🌐
MDBootstrap
mdbootstrap.com › standard › material design for bootstrap 5 & vanilla javascript
MDB - FileUpload Plugin - Support for blob and base64 string - Material Design for Bootstrap
Final URL: "blob:http://localhost:4200/65d8ef50-98b9-4824-9b90-bdecf877d5e1"This is also happening with base64 strings or images returned by an api that don't have a file ending (for example http://myapi.com/getPicture/23) won't work while (http://myapi.com/getPicture/23.jpg) is working fine. ... The name of input can be a bit confusing in this case, but it's not possible to use an actual javascript file object as a default file added to the HTML file input.
Top answer
1 of 16
1181

The atob function will decode a base64-encoded string into a new string with a character for each byte of the binary data.

const byteCharacters = atob(b64Data);

Each character's code point (charCode) will be the value of the byte. We can create an array of byte values by applying this using the .charCodeAt method for each character in the string.

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

You can convert this array of byte values into a real typed byte array by passing it to the Uint8Array constructor.

const byteArray = new Uint8Array(byteNumbers);

This in turn can be converted to a Blob by wrapping it in an array and passing it to the Blob constructor.

const blob = new Blob([byteArray], {type: contentType});

The code above works. However the performance can be improved a little by processing the byteCharacters in smaller slices, rather than all at once. In my rough testing 512 bytes seems to be a good slice size. This gives us the following function.

const 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;
}
const blob = b64toBlob(b64Data, contentType);
const blobUrl = URL.createObjectURL(blob);

window.location = blobUrl;

Full Example:

Show code snippet

const 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;
}

const contentType = 'image/png';
const b64Data = 'iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==';

const blob = b64toBlob(b64Data, contentType);
const blobUrl = URL.createObjectURL(blob);

const img = document.createElement('img');
img.src = blobUrl;
document.body.appendChild(img);
Run code snippetEdit code snippet Hide Results Copy to answer Expand

2 of 16
666

Here is a more minimal method without any dependencies or libraries.
It requires the new fetch API. (Can I use it?)

var url = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="

fetch(url)
.then(res => res.blob())
.then(console.log)
Run code snippetEdit code snippet Hide Results Copy to answer Expand

With this method you can also easily get a ReadableStream, ArrayBuffer, text, and JSON.
(fyi this also works with node-fetch in Node)

As a function:

const b64toBlob = (base64, type = 'application/octet-stream') => 
  fetch(`data:${type};base64,${base64}`).then(res => res.blob())

But I would encourage you to don't use base64 in the first place. There are better ways to send and receive binary data. JSON isn't always the best option. it takes up more bandwidth and waste processing time (de)encodeing stuff. Us eg canvas.toBlob instead of canvas.toDataURL and use FormData to send binary files. you can also return back a multipart payload and decode it using await response.formData() that is coming from a server response. FormData can go both ways.


I did a simple performance test towards Jeremy's ES6 sync version.
The sync version will block UI for a while. keeping the devtool open can slow the fetch performance

Show code snippet

document.body.innerHTML += '<input autofocus placeholder="try writing">'
// get some dummy gradient image
var img=function(){var a=document.createElement("canvas"),b=a.getContext("2d"),c=b.createLinearGradient(0,0,1500,1500);a.width=a.height=3000;c.addColorStop(0,"red");c.addColorStop(1,"blue");b.fillStyle=c;b.fillRect(0,0,a.width,a.height);return a.toDataURL()}();


async function perf() {
  
  const blob = await fetch(img).then(res => res.blob())
  // turn it to a dataURI
  const url = img
  const b64Data = url.split(',')[1]

  // Jeremy Banks solution
  const 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;
  }

  // bench blocking method
  let i = 500
  console.time('blocking b64')
  while (i--) {
    await b64toBlob(b64Data)
  }
  console.timeEnd('blocking b64')
  
  // bench non blocking
  i = 500

  // so that the function is not reconstructed each time
  const toBlob = res => res.blob()
  console.time('fetch')
  while (i--) {
    await fetch(url).then(toBlob)
  }
  console.timeEnd('fetch')
  console.log('done')
}

perf()
Run code snippetEdit code snippet Hide Results Copy to answer Expand

🌐
Syncfusion
syncfusion.com › forums › 167655 › open-file-as-blob-or-stringbase64
Open file as Blob or String[Base64] | Angular - EJ 2 Forums | Syncfusion®
July 28, 2021 - SIGN IN To post a reply. ... Thank you for contacting Syncfusion support. You can load Base64 data in the PDF Viewer using load method.
🌐
Libraries.io
libraries.io › bower › ng-base64
ng-base64 on Bower - Libraries.io - security & maintenance data for open source software
October 23, 2015 - angular service for ecoding/decoding blobs/strings into base64 format - a JavaScript package on Bower
🌐
npm
npmjs.com › package › blob-to-base64
blob-to-base64 - npm
February 26, 2019 - Convert Blob to base64. Latest version: 1.0.2, last published: 7 years ago. Start using blob-to-base64 in your project by running `npm i blob-to-base64`. There are 5 other projects in the npm registry using blob-to-base64.
      » npm install blob-to-base64
    
Published: Feb 26, 2019
Version: 1.0.2
🌐
Medium
geekjob.medium.com › convert-blob-to-base64-in-js-e5808fd69961
Convert Blob to Base64 in JS - Fullstack CTO - Medium
March 22, 2023 - const blob2base64 = (blob, mimeType) => { return new Promise((resolve, reject) => { const reader = new FileReader(); reader.onloadend = () => { const dataUrlPrefix = `data:${mimeType};base64,`; const base64WithDataUrlPrefix = reader.result; const base64 = base64WithDataUrlPrefix.replace(dataUrlPrefix, ''); resolve(base64); }; reader.onerror = reject; reader.readAsDataURL(blob); }); }; const obj = { hello: 'world' }; const mimeType = 'application/json'; const blob = new Blob([JSON.stringify(obj, null, 2)], { type: mimeType }); blob2base64(blob, mimeType).then(base64 => { console.log(base64); }); // or const base64 = await blob2base64(blob, mimeType); console.log(base64);
🌐
Pretagteam
pretagteam.com › question › angular2-convert-blob-to-long-base64
Angular2 - Convert Blob to long base64 - Pretag
August 30, 2021 - In this JavaScript quick tutorial, we’ll learn how to select a file using a File input control to convert it into a Base64 URL, also add a View button to preview the selected file by opening in the new Chrome tab by creating a BLOB url.if(typeof __ez_fad_position != 'undefined'){__ez_fad_position('div-gpt-ad-freakyjolly_com-medrectangle-3-0')};,Finally, we’re done with a tutorial on how to convert the selected file into a Blob url, and append the link to open the selected file in a new browser tab.,We have already discussed how to convert the selected file into a Base64 string URL here, you can check the complete tutorial in Angular.if(typeof __ez_fad_position != 'undefined'){__ez_fad_position('div-gpt-ad-freakyjolly_com-medrectangle-4-0')};