From blob to base64 string

A demo to show how to convert a blob response object to a base64 string and set it as an image src in plain javascript.

by wilt

HTML

<div id='container'>
</div>

JavaScript

const createImageFromBase64 = function(event) {
  const img = document.createElement('img');
  img.src = this.result;
  document.getElementById('container').appendChild(img);
}

const onLoadReadBlobAsBase64 = function(event) {
  const blob = this.response;
  const reader = new FileReader();
  reader.onloadend = createImageFromBase64;
  reader.readAsDataURL(blob);
}

var xhr = new XMLHttpRequest();
xhr.open("GET", "https://i.imgur.com/7JvpXg3.jpg");
xhr.responseType = "blob";
xhr.onload = onLoadReadBlobAsBase64;
xhr.send();