【译】What is Blob?

Posted Jun 28, 20204 min read

Original address: https://codeburst.io/javascri...

Author:Dornhoth

If you can already allow a user to download certain files from your website, then you may have encountered the Blob type. You may have checked some examples online and modified them, but did not think much about what this blob is. As long as it works...

This knowledge can show the difference between junior developers and advanced developers. Or, as a junior developer, you will stand out because of curiosity and desire to learn. Even if you are not preparing for an interview, a clear and simple understanding of what Blob is can help you understand the complex code encountered in the next time you compress a PDF file, so let s get started:

usage

To download some simple text, you can do this:

<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <title>Blobs</title>
  <script src="index.js"></script>
</head>

<body>
  <button id="button">Link</button>
</body>

</html>

const download =(fileName, file) => {
  const element = document.createElement('a');
  element.href = file;
  element.download = fileName;
  element.target ='_blank';
  element.click();
  element.remove();
}

document.addEventListener('click', async event => {
  if(event.target.id ==='button') {
    const fileName ='test.txt';
    download(fileName,'data:text/json;charset=utf-8,File to download');
  }
});

On the other hand, for more complex files, this is not enough. If we want to download the generated PDF file, we must do this(this example uses jsPDF):

<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <title>Blobs</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.5/jspdf.debug.js"></script>
  <script src="index.js"></script>
</head>

<body>
  <button id="button">Link</button>
</body>

</html>

const download =(fileName, blob) => {
  const element = document.createElement('a');
  const url = window.URL.createObjectURL(blob);
  element.href = url;
  element.download = fileName;
  element.target ='_blank';
  element.click();
  element.remove();
}

document.addEventListener('click', async event => {
  if(event.target.id ==='button') {
    const doc = new jsPDF();
    const fileName ='test.pdf';
    doc.text('Hello world!');
    const blob = new Blob([doc.output()]);
    download(fileName, blob);
  }
});

What is Blob?

Blobs are not unique to JavaScript. Initially, Blobs were created for use in database management systems. This type was created in the 1970s and is used to store large files such as audio, images, or video. These files are too large to be stored in regular database fields. So this term actually refers to "Binary Large Object".

In JavaScript, Blob is used to represent files as immutable raw data. In the console, the blob we created in the previous example looks like this:

image

As you can see, Blob has two properties:size and type. The size is the data size in bytes. The type is a string of the MIME type of the package. I did not give any type when creating the Blob, but I should do this:

const blob = new Blob([doc.output()], {type:'application/pdf' });

Now my Blob also has a type:

image

What's in Blob?

JavaScript Blob provides some methods to access their content. One of them is the text method, which returns a Promise parsing of the content of the blob as text(technically USVString).

document.addEventListener('click', async event => {
  if(event.target.id ==='button') {
    const doc = new jsPDF();
    doc.text('Hello world!');
    const blob = new Blob([doc.output()], {type:'application/pdf' });
    const blobAsText = await blob.text();
    console.log(blobAsText);
  }
});

This gives us a rather incomprehensible content:

%PDF-1.3
3 0 obj
<</Type /Page
/Parent 1 0 R
/Resources 2 0 R
/MediaBox [0 0 595.28 841.89]
/Contents 4 0 R
>>
endobj
4 0 obj
<</Length 67>>
stream
0.57 w
0 G
BT
/F1 16 Tf
18.4 TL
0 g
NaN NaN Td
(Hello world!) Tj
ET
endstream
endobj
1 0 obj
<</Type /Pages
/Kids [3 0 R]
/Count 1
>>
endobj
5 0 obj
<</BaseFont/Helvetica/Type/Font
/Encoding/WinAnsiEncoding
/Subtype/Type1>>
endobj
6 0 obj
...

There are not many things you can do, but it gives you a chance to understand what the file looks like.

There are two other methods that allow you to access the content of the blob:

  • arrayBuffer, will return a Promise to ArrayBuffer
  • stream, will return a readable stream(ReadableStream)

Operation Blob

You regularly receive files from HTTP requests. If you use the fetch API, you need to use the blob method on the body to read the blob from the response:

document.addEventListener('click', async event => {
  if(event.target.id ==='button') {
    fetch('https://whatever/doc.pdf')
    .then(response => response.blob())
    .then(blob => {
      download('test.pdf', blob);
    });
  }
});

In the previous example, we created a PDF file using the library and created a blob from it.

You can also create a blob from another blob. You can only slice the original blob, which means that only a portion of its bytes are returned.

document.addEventListener('click', async event => {
  if(event.target.id ==='button') {
    const blob = new Blob(['some text'], {type:'application/pdf' });
    const slicedBlob = blob.slice(5, 9);
    const blobAsText = await blob.text();
    const slicedBlobAsText = await slicedBlob.text();

    console.log(`Original Blob:${blobAsText}`);
    console.log(`Sliced   Blob:${slicedBlobAsText}`);
  }
});

image

This may be useful for very simple blobs, but for more complex files, this may damage your files and make the sliced blobs unreadable.

I hope you understand the usage of Blob now. This is a very simple data type used to represent files as raw data. If you want to know more details, you can check the documentation:

https://developer.mozilla.org/en-US/docs/Web/API/Blob