Blobs in JavaScript

Apr 29, 2020

A blob is an object that contains arbitrary bytes. The Blob class is part of the File API for browsers: the JavaScript File class is a subclass of Blob. So when you get a file instance from an <input type="file">, that is an instance of Blob.

const input = document.querySelector('input[type="file"]');
const file = input.files[0];

file instanceof File; // true
file instanceof Blob; // true

Like FileReader, the Blob class is well supported in different browsers, but not in Node.js. Node.js buffers are analagous to blobs in that they store arbitrary bytes, but they have a completely separate API.

Blob Data Urls

Blobs have a neat createObjectUrl() function that is often used for previewing uploaded images. Given a blob, URL.createObjectURL() creates a URL for that blob that you can use with attributes like src or href.

For example, if you click on the below file input and select an image, you'll see a preview of the selected image.

Below is the JavaScript that powers the above input. It uses URL.createObjectURL() to create a local URL for the uploaded file, without actually uploading the file to a server.

const input = document.querySelector('#data-url-example');

input.addEventListener('change', () => {
  const file = input.files[0];
  const url = URL.createObjectURL(file);

  document.querySelector('#data-url-container').innerHTML = `
    <img src="${url}" />

Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Fundamentals Tutorials