How To Use Blob Object in JavaScript



In this article, you will learn how to use Blob object in JavaScript.

What is Blob?

Blob is a JavaScript object for handling Binary Large Objects.
In the computer, all data is managed by 0 and 1, and the data represented by 0 and 1 is binary data.
Blob can also use a wide variety of data.

Since Blob is binary data, it can handle not only text files but also files in various formats such as images and PDFs.

By making the JavaScript processing result into Blob, it is also possible to save it as a data file.
Therefore, it is easy to use when you want to download the processing result.

The syntax is below.

const blob = new Blob([JSON.stringify(obj, null, 2)], {type : 'application/json'});

Sample Code

The following is a sample code that makes the processing result into a Blob, saves it as a data file, and specifies the saved file as the link destination of the download link.

<!DOCTYPE html>
<html lang="ja">
  <meta charset="UTF-8">
  <div id="result"></div>
    let blob = new Blob(['foobar'],{type:"text/plain"});
    let link = document.createElement('a');
    link.href = URL.createObjectURL(blob); = 'foobar.txt';
    link.innerText = 'Download';
    const result = document.getElementById('result');