Blobs are rarely used in general Web development, but bloBs can meet specific requirements in some scenarios. Blob: Binary Large Object. The Blob concept is used in some databases. For example, the Blob type in MYSQL represents a container for binary data. On the Web, Blob objects represent immutable raw data of file-like objects. In layman’s terms, a Blob object is binary data, but it is binary data of file-like objects, so you can manipulate a Blob object just as you would a File object, which in fact inherits from a Blob.

Basic usage of Blob

create

Blob objects can be created using a Blob constructor:

Blob(blobParts[, options])
Copy the code

Parameter Description:

BlobParts: An array type in which each item in the array is joined to form the data of the Blob object. Each item in the array can be an ArrayBuffer, an ArrayBufferView, a Blob, or a DOMString.

Options: The dictionary format is optional. You can specify the following attributes:

  • Type. The default value is"", which represents the MIME type of the array content to be put into the BLOB.
  • Endings, whose default value is “transparent”, specifies the end of the line\nHow the string is written. It is one of two values: “native”, indicating that the line terminator is changed to a newline suitable for the host operating system file system; “Transparent”, which keeps the terminator saved in the BLOB unchanged.

Such as:

    var data1 = "a";
    var data2 = "b";
    var data3 = "
      
This is a blob
"
; var data4 = { "name": "abc"}; var blob1 = new Blob([data1]); var blob2 = new Blob([data1, data2]); var blob3 = new Blob([data3]); var blob4 = new Blob([JSON.stringify(data4)]); var blob5 = new Blob([data4]); var blob6 = new Blob([data3, data4]); console.log(blob1); // output: Blob {size: 1,type: ""} console.log(blob2); // output: Blob {size: 2,type: ""} console.log(blob3); // output: Blob {size: 44,type: ""} console.log(blob4); // output: Blob {size: 14,type: ""} console.log(blob5); // output: Blob {size: 15,type: ""} console.log(blob6); // output: Blob {size: 59,type: ""} Copy the code

Size represents the number of bytes of data contained in the Blob object. Note here that blobs created using strings are different from normal objects. Blob4 uses json.stringify to convert a data4 object to a JSON string, while Blob5 is created directly from data4, with sizes 14 and 15 respectively. Blob4 size equals 14 is easy to understand because json.stringify (data4) results in :” {“name”:” ABC “}”, which is exactly 14 bytes (excluding the outermost quotes). How is the size of blob5 equal to 15 calculated? In fact, when you create a Blob object from a normal object, you call the toString() method of the normal object to get the string data and then create the Blob object. So, the data stored in blob5 is “[Object object]”, which is 15 bytes (excluding the outermost quotes).

Slice method

A Blob object has a slice method that returns a new Blob object containing data within a specified range from the source Blob object.

slice([start[, end[, contentType]]])
Copy the code

Parameter Description:

Start: Optional, representing the subscript in the Blob and the starting position of the first byte to be copied into the new Blob. If a negative number is passed in, the offset will be calculated from the end of the data to the front.

End: Optional, representing a subscript of the Blob. The subscript -1 will be the last byte copied into the new Blob. If you pass in a negative number, the offset will be calculated from the end of the data from back to front.

ContentType: Optional, give the new Blob a new document type. This will set its type attribute to the value passed in. Its default value is an empty string.

Such as:

    var data = "abcdef"; var blob1 = new Blob([data]); Var blob2 = blob1. Slice (0, 3); console.log(blob1); // output: Blob {size: 6,type: ""} console.log(blob2); // output: Blob {size: 3,type: ""}
Copy the code

With the slice method, a new BLOB object with size equal to 3 is created from blob1.

Blob usage scenarios

Shard to upload

As mentioned earlier, File inherits from Blob, so we can call slice to slice large files for long transmission. The code is as follows:

functionuploadFile(file) { var chunkSize = 1024 * 1024; Var totalSize = file.size; var chunkQuantity = Math.ceil(totalSize/chunkSize); // Total number of fragments var offset = 0; Var reader = new FileReader(); reader.onload =function(e) {
    var xhr = new XMLHttpRequest();
    xhr.open("POST"."http://xxxx/upload? fileName="+file.name);
    xhr.overrideMimeType("application/octet-stream");
    
    xhr.onreadystatechange = function() {
      if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
        ++offset;
        if(offset === chunkQuantity) {
          alert("Upload completed");
        } else if(offset === chunkQuantity-1){ blob = file.slice(offset*chunkSize, totalSize); / / upload the last piece of reader. ReadAsBinaryString (blob); }else{ blob = file.slice(offset*chunkSize, (offset+1)*chunkSize); reader.readAsBinaryString(blob); }}else {
        alert("Upload error"); }}if(xhr.sendAsBinary) { xhr.sendAsBinary(e.target.result); // e.target.result is the fragmented binary data read}else {
      xhr.send(e.target.result);
    }
  }
   var blob = file.slice(0, chunkSize);
   reader.readAsBinaryString(blob);
}
Copy the code

This code can be further enriched by displaying the current upload progress, using multiple XMLHttpRequest objects to upload objects in parallel (passing the location parameters of the shard data to the server), and so on.

Blob URL

A Blob URL is a Blob protocol URL in the following format:

blob:http://XXX
Copy the code

Blob urls can be created with url.createObjecturl (Blob). In most scenarios, we can use Blob urls just like Http urls. Common scenarios are: as a file download address and as an image resource address.

  • File download address
<! DOCTYPE html> <html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Blob Test</title>
    <script>
        function createDownloadFile() {
            var content = "Blob Data";
            var blob = new Blob([content]);
            var link = document.getElementsByTagName("a") [0]; link.download ="file"; link.href = URL.createObjectURL(blob); } window.onload = createDownloadFile; < / script > < / head > < body > < a > download < / a > < / body > < / HTML >Copy the code

Click the Download button and the browser will download a file called File with the contents of Blob Data. With Blob objects, we can dynamically generate files in our front-end code for the browser to download. Open the Chrome debug window, and under the Elements TAB you can see that the generated Blob URL is:

  • Image resource address

Create a Blob URL for the image file and assign it toTags:

<! DOCTYPE html> <html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Blob Test</title>
    <script>
        function handleFile(e) {
            var file = e.files[0];
            var blob = URL.createObjectURL(file);
            var img = document.getElementsByTagName("img") [0]; img.src = blob; img.onload =function(e) { URL.revokeObjectURL(this.src); // Release the object created by createObjectURL# #
            }
        }
    </script>
</head>

<body>
    <input type="file" accept="image/*" onchange="handleFile(this)" />
    <br/>
    <img style="width:200px; height:200px">
</body>

</html>
Copy the code

The image selected in input will be displayed inAs shown in the figure:

The request for this Blob URL can also be found in the Network TAB:

This request information is almost identical to the Http URL we use to get the image. We can also load image resources using the Data URL:

<! DOCTYPE html> <html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Blob Test</title>
    <script>
        function handleFile(e) {
            var file = e.files[0];
            var fileReader = new FileReader();
            var img = document.getElementsByTagName("img") [0]; fileReader.onload =function(e) {
                img.src = e.target.result;
            }
            fileReader.readAsDataURL(file);
        }
    </script>
</head>

<body>
    <input type="file" accept="image/*" onchange="handleFile(this)" />
    <br/>
    <img style="width:200px; height:200px">
</body>

</html>
Copy the code

FileReader’s readAsDataURL generates a DataURL as shown:

Data URL should be familiar to everyone. One of the measures in Web performance optimization is to embed small images in HTML files directly with Base64 encoding, which is actually to use Data URL to obtain embedded image Data.

So what’s the difference between a Blob URL and a Data URL?

  1. Blob urls tend to be short in length, but Data urls tend to be long because they store base64 encoded Data directly. As shown in the figure above, browsers display Data urls with ellipses (…). . When large images are explicit, using Blob urls yields better possibilities.
  2. Blob urls make it easy to retrieve source data using XMLHttpRequest, for example:
var blobUrl = URL.createObjectURL(new Blob(['Test'] and {type: 'text/plain'}));
var x = new XMLHttpRequest();
// 如果设置x.responseType = 'blob', will return a Blob object instead of text: // x.reesponseType ='blob';
x.onload = function() { alert(x.responseText); // output Test}; x.open('get', blobUrl);
x.send();
Copy the code

For Data urls, not all browsers support XMLHttpRequest to retrieve the source Data. 3. The Blob URL is only used within the current application. Copying the Blob URL to the address bar of the browser does not obtain data. Data urls, by contrast, are portable and can be used in any browser.

Blob urls can also be used as web addresses for other resources, such as HTML files and JSON files. To ensure that the browser can correctly parse the file type returned by the Blob URL, specify the corresponding type when creating the Blob object:

// Create HTML file Blob URL var data ="
      
This is a blob
"
; var blob = new Blob([data], { type: 'text/html'}); var blobURL = URL.createObjectURL(blob); // Create JSON file Blob URL var data = {"name": "abc" }; var blob = new Blob([JSON.stringify(data)], { type: 'application/json' }); var blobURL = URL.createObjectURL(blob); Copy the code

Welcome to pay attention to my public number: the big front of old cadres, receive 21 big front selection books!