How To Use Blob Object in JavaScript | Plantpot

How To Use Blob Object in JavaScript

Web Dev
Sponsored links

In this article, I will introduce 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'});
Sponsored links

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">
<head>
  <meta charset="UTF-8">
</head>
<body>
  <div id="result"></div>
  <script>
    let blob = new Blob(['foobar'],{type:"text/plain"});
    let link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = 'foobar.txt';
    link.innerText = 'Download';
    const result = document.getElementById('result');
    result.appendChild(link);
  </script>
</body>
</html>