Blob

JavaScript Blob

JavaScript Blobs are a data structure used to represent and manipulate raw data in various formats, such as binary or text data. A Blob (Binary Large Object) is an immutable, lightweight object that can store chunks of data efficiently, making it suitable for handling large files, such as images, audio, or video files. (JavaScript Blob是一种数据结构,用于表示和处理各种格式的原始数据,例如二进制或文本数据。Blob (二进制大型对象)是一个不可变的轻量级对象,可以有效地存储数据块,使其适用于处理大型文件,如图像、音频或视频文件。)

Blobs are supported in modern web browsers and can be used for a variety of purposes, including:

File handling: Blobs can be used to read, write, and manipulate files, enabling tasks like file uploads, downloads, and file reading in web applications.Data manipulation: Blobs are useful when working with binary data, such as image or video processing, by allowing you to manipulate the data directly in JavaScript.Asynchronous processing: Blobs can be used in combination with Web Workers to perform complex data processing tasks in the background, without blocking the main browser thread.

Constructing a Blob

Constructing a Blob (构造Blob)

For constructing a Blob from other data and non-blob objects, the Blob() constructor is used. Its syntax is the following:

new Blob(blobParts, options);

Now, let’s check out an example of creating Blob from a string:

// create Blob from string
let blob = new Blob(["<html>…</html>"], {
	type: 'text/html'
});
// important: the first argument must be an array [...]

In the next example, it is created from a typed array and strings:

// create Blob from a typed array and strings
let welcome = new Uint8Array([89, 101, 108, 99, 111, 109, 101]); // "Welcome" in binary form
let blob = new Blob([welcome, ' to ', 'w3cdoc'], {type: 'text/plain'});

The Blob slices can be extracted with:

blob.slice([byteStart], [byteEnd], [contentType]);

The arguments here are like array.slice. Negative numbers can also be used. Please, note that data can’t be changed directly in the Blob. Yet, it is possible to slice parts of the Blob, creating new Blob objects from them, mixing them into a new Blob, and so on. (这里的参数类似于array.slice。 也可以使用负数。 请注意,数据不能直接在Blob中更改。 但是,可以对Blob的部分进行切片,从中创建新的Blob对象,将它们混合到新的Blob中,依此类推。)

Blob as URL

Blob as URL (Blob作为URL)

The Blob is flexible: you can, also, use it as URL for <img>, <a>, and other tags. The Blob objects can also be downloaded and uploaded with the help of type. It naturally transforms into Content-Type for network requests.

Let’s have a look at the following example:

<!DOCTYPE html>
<html>
 <head>
   <title>Title of the Document</title>
 </head>
 <body>
   <!-- The download attribute causes the browser to download instead of navigating -->
   <a download="welcome.txt" href='#' id="link">Download</a>
   <script>
     let blob = new Blob(["Welcome to w3cdoc"], {type: 'text/plain'});
     link.href = URL.createObjectURL(blob);
   </script>
 </body>
</html>

Also, in JavaScript, a link can be created dynamically, simulating a click by link.click(). After this action, the download will start automatically. (此外,在JavaScript中,可以动态创建链接,模拟link.click ()的点击。执行此操作后,下载将自动开始。)

Here is another example without the usage of HTML:

<!DOCTYPE html>
<html>
 <head>
   <title>Title of the Document</title>
 </head>
 <body>
   <script>
     let link = document.createElement('a');
     link.download = 'welcome.txt';
     let blob = new Blob(['Welcome to w3cdoc'], {type: 'text/plain'});
     link.href = URL.createObjectURL(blob);
     link.click();
     URL.revokeObjectURL(link.href);      
   </script>
 </body>
</html>

A created URL can only be valid inside the current document. It allows referencing the Blob in <a>, <img>.

But, note that there can be a significant side-effect. Particularly, when there exists a mapping for a Blob, it can reside in the memory. The browser is not able to get rid of it. (但是,请注意,可能会有明显的副作用。特别是,当存在Blob的映射时,它可以驻留在内存中。浏览器无法删除它。)

On document onload, the mapping is automatically cleared, so, then, objects will be freed. But, in case of a long-living app, it won’t happen soon. So, in case of creating a URL, the Blob can hang in memory. (在文档加载时,映射会自动清除,因此,对象将被释放。 但是,如果是长寿命的应用程序,这种情况不会很快发生。 因此,在创建URL的情况下, Blob可以挂在内存中。)

With URL.revokeObjectURL(url), you can remove the reference from the internal mapping, letting the Blob to be deleted, freeing the memory. (使用URL.revokeObjectURL (url) ,可以从内部映射中删除引用,从而删除Blob ,释放内存。)

To Base 64

To Base 64 (至Base 64)

An alternative option to URL.createObjectURL is converting Blob into a base-64 encoded string. (URL.createObjectURL的另一个选项是将Blob转换为base-64编码的字符串。)

Such encoding illustrates binary data as a string of an ultra-safe readable characters with ASCII-codes from 0 to 64. Fortunately, such encoding can be used in “data-urls”. (这种编码将二进制数据示出为具有从0到64的ASCII码的超安全可读字符的字符串。幸运的是,这种编码可以在“data-urls”中使用。)

A data-url form is data:[<mediatype>][;base64],<data>. They can be used anywhere with regular URLs.

The string will be decoded by the browser, and the image will be shown. For transforming a Blob into base-64, the built-in FileReader is used. It is capable of reading data from Blobs in multiple formats. (字符串将由浏览器解码,并显示图像。 为了将Blob转换为base-64 ,使用了内置的FileReader。 它能够以多种格式从Blob中读取数据。)

The demo of downloading a blob via base-64 will look like this:

<!DOCTYPE html>
<html>
 <head>
   <title>Title of the Document</title>
 </head>
 <body>
   <script>
     let link = document.createElement('a');
     link.download = 'welcome.txt';
     let blob = new Blob(['Welcome to w3cdoc'], {type: 'text/plain'});
     let reader = new FileReader();
     reader.readAsDataURL(blob); // converts ta blob to base64 and calls onload
     reader.onload = function() {
       link.href = reader.result; // data url
       link.click();
     };      
   </script>
 </body>
</html>

Both of the ways are handy, but URL.createObjectURL(blob) is much more straightforward. (这两种方法都很方便,但URL.createObjectURL (BLOB)要简单得多。)

Image to Blob

Image to Blob (图像到Blob)

It is possible to generate Blob of an image part, a whole image, or take a page screenshot. It is, particularly, useful for uploading it somewhere. Image operations are carried out through the <canvas> element.

As a first step, it’s necessary to draw an image on canvas with canvas.drawImage. Then, gon on with calling the canvas method, which generates a .toBlob(callback, format, quality) and runs callback with it when completed. (首先,有必要使用canvas.drawImage在画布上绘制图像。 然后,继续调用canvas方法,该方法生成.toBlob (回调、格式、质量)并在完成时使用它运行回调。)

To ArrayBuffer

To ArrayBuffer (至ArrayBuffer)

The Blob constructor helps to generate a blob from anything, including BufferSource. (Blob构造函数有助于从任何内容(包括BufferSource )生成blob。)

When you want to implement low-level processing, the lowest-level ArrayBuffer can be used from FileReader, like this:

// getting arrayBuffer from blob
let fileReader = new FileReader();
fileReader.readAsArrayBuffer(blob);
fileReader.onload = function (event) {
	let arrayBuffer = fileReader.result;
};

Summary

Summary (概要)

As you know, ArrayBuffer, BufferSource, and Uint8Array are considered binary data. A Blob is a binary data with type. Therefore, Blob is quite convenient for downloading and uploading operations, common in the browser. (如您所知, ArrayBuffer、BufferSource和Uint8Array被视为二进制数据。Blob是具有类型的二进制数据。因此, Blob对于下载和上传操作非常方便,这在浏览器中很常见。)

Web-request methods such as fetch, XMLHttpRequest, and more can natively operate with Blob. (Web请求方法(如fetch、XMLHttpRequest等)可以使用Blob进行本机操作。)

Also, Blob can be converted to low-binary data types. (此外, Blob可以转换为低二进制数据类型。)



请遵守《互联网环境法规》文明发言,欢迎讨论问题
扫码反馈

扫一扫,反馈当前页面

咨询反馈
扫码关注
返回顶部