Javascript 简明教程

JavaScript - Blob

What is blob in JavaScript?

在 JavaScript 中, Blob 是一个对象,它是一组字节,表示存储在文件中的数据。我们可以轻松地将 Blob 对象的内容读取为 ArrayBuffer,因此它非常适合存储二进制数据。 Blob 对象用于处理原始二进制数据,我们可以从纯文本、文件数据等创建这些数据。

In JavaScript, a Blob is an object that is a group of bytes representing the data stored in the file. We can easily easily read the content of the Blob object as an ArrayBuffer, so it is very useful to store the binary data. The Blob object is used to handle the raw binary data, which we can create from the plain text, file data, etc.

Syntax

用户可以遵循以下语法来使用 Blob() 构造函数创建一个 blob 对象。

Users can follow the syntax below to use the Blob() constructor to create a blob object.

new Blob(BlobContent, Options);

OR

new Blob(BlobContent, {type: Type of the Blob content});

在上面的语法中,Blob() 构造函数采用两个参数并返回 Blob 对象的实例。开发人员可以根据 BlobContent 设置“类型”选项的值。

In the above syntax, Blob() constructor takes two parameters and returns an instance of the Blob object. Developers can set the values of the 'type' option based on the BlobContent.

Parameters

Blob() 构造函数采用以下两个参数。

The Blob() constructor takes two parameters, as given below.

  1. BlobContent − It is a text, data, or file content.

  2. Options − It is an optional object containing various options for BlobContent.

“type”是 Options 对象中一个重要的属性。它以值的格式包含 BlobContent 的 MIME 类型。例如,要在 blob 对象中存储纯文本,可以用 'text/plain' 作为 MIME 类型;对于图像,可以用 'image/jpg' 或 'image/png' 等。

The 'type' is an important property in the Options object. It contains the MIME-type of the BlobContent as a value. For example, to store plain text in the blob object, you can use 'text/plain' as a MIME type; for images, you can use 'image/jpg' or 'image/png', etc.

Example

在下面的示例代码中,我们使用了 blob() 构造函数创建了一个 blob 对象。我们传递了 'Hello World!' 字符串作为第一个参数,'text/plain' MIME 类型作为 blob() 构造函数的第二个参数。

In the below example code, we have used the blob() constructor to create a blob object. We have passed the 'Hello World!' string as a first parameter and the 'text/plain' MIME type for the content as a second parameter of the blob() constructor.

然后,我们创建了 FileReader() 对象的实例,并使用 readAsText() 方法读取 blob 对象的内容。在输出中,我们可以看到它打印了纯文本,这是 blob 对象的内容。

After that, we have created the instance of the FileReader() object and used the readAsText() method to read the content of the blob object. In the output, we can see that it prints the plain text, which is the content of the blob object.

<html>
<body>
   <h2> JavaScript - Blob Object </h2>
   <h3 id = "output"> </h3>
   <script>
      var data = "Hello World";
      var blob = new Blob([data], {
         type: 'text/plain'
      });

      // Using the fileReader object to read the blob
      var reader = new FileReader();
      reader.addEventListener("loadend", function (e) {
         var text = reader.result;
         document.getElementById("output").innerHTML = text;
      });
      // Start reading the blob as text
      reader.readAsText(blob);
   </script>
</body>
</html>

Blob URLs

在上述部分中,我们学习了如何使用 blob 对象。此外,我们还可以使用 blob 对象创建 URL。任何特定 URL 都指向本地文件系统中的文件,blob URL 指向 blob 对象的内容。此外,我们可以将 blob URL 用作包含 <a> 或 <img> 标记的实际 URL。

In the above section, we have learned to use the blob object. Furthermore, we can also create the URL using the blob object. As any particular URL refers to the file in the local file system, the blob URL referes to the content of the blob object. Also, we can use the blob URL as an actual URL with the <a> or <img> tag.

让我们看一如下面的示例,以从 blob 对象创建 URL。

Let’s take a look at the example below to create a URL from the blob object.

Example: Rendering text content using the Blob URL

在下面的示例中,我们创建了 blob 对象的实例,并传递了文本内容作为参数。然后,我们使用 createObjectURL() 方法创建了 blob URL。

In the example below, we have created the instance of the blob object and passed text content as a parameter. After that, we used the createObjectURL() method to create a blob URL.

接下来,我们用 blob URL 更新了 '<a>' 的 'href' 属性的值。在输出中,当您点击 URL 时,它会向您显示存储在 blob 对象中的内容。

Next, we have updated the value of the 'href' attribute of the '<a>' with the blob URL. In the output, when you click the URL, it shows you the content stored in the blob object.

<html>
<body>
   <h2> JavaScript - Blob URL </h2>
   <a href = "#" id = "download"> Download Text File </a>
   <script>
      // Creating file using Blob object
      var data = "This file contains the content of the blob object.";
      var blob = new Blob([data], {
         type: 'text/plain'
      });
      // Creating URL from Blob object
      var url = URL.createObjectURL(blob);
      var a = document.getElementById("download");
      // Updating the `href` attribute's value
      a.href = url;
   </script>
</body>
</html>

Example: Rendering an Image Using the Blob URL

在这个示例中,我们使用文件输入获取了图像作为输入。每当用户上传图像时,我们就使用文件内容创建一个 blob 对象。

In this example, we have used the file input to get the image as input. Whenever the user uploads the image, we create the blob object using the file content.

然后,我们从 blob 对象创建一个 URL,并用它作为 '' 标记的 'src' 属性的值,以便在网页上呈现图像。

After that, we create a URL from the blob object and use it as a value of the 'src' attribute of the '' tag to render the image on the web page.

<html>
<body>
   <h2> JavaScript – Blob URL </h2>
   <h3> Upload image file </h3>
   <input type = "file" id = "fileInput" />
   <div id = "output"> </div>
   <script>
      // Read the file and create a blob
      document.getElementById('fileInput').addEventListener('change', function () {
         var file = this.files[0];
         var reader = new FileReader();
         reader.onload = function () {
            // Create a blob
            var blob = new Blob([new Uint8Array(this.result)], { type: file.type });
            // Create an object URL
            var url = URL.createObjectURL(blob);
            // Set the object URL as the source of an image
            document.getElementById('output').innerHTML = '<img src="' + url + '" />';
        };
        reader.readAsArrayBuffer(file);
    });
</script>
</body>
</html>

Blob Advantages & Disadvantages

下面列举了使用 blob 对象的一些优点和缺点。

Here are some advantages and disadvantages of using the blob objects.

Advantages

  1. Blob objects are ideal for handling large binary data files on the web.

  2. Developers can fetch the data in chunks by using the blob objects, which improves the performance of the application.

  3. Blob objects can be used with the File API to perform the file operations in the browser.

Disadvantages

  1. Large blob objects can consume significant memory and resources, which can impact the overall application performance and use experience.

  2. Handling the binary data using the blob object can introduce security concerns to the code.

  3. Older browsers do not support blob.