js Blob object in general usage

Some time ago Research binary stream Photo Gallery encountered a Blob object in here to do some notes.

Web development in general, rarely used Blob, but Blob meet the special needs under some scenarios. Large Objects Blob, Binary Large Object abbreviation, representing the binary type. Blob concept has to use in some database, for example, the BLOB MYSQL Based on a container representing the type of binary data. In Web, the object Blob type of representation of the original data file-like objects are immutable, popular point that is Blob objects are binary data, but it is a binary data file-like object, and therefore can operate File object as the operation Blob object In fact, File inherits from Blob.

Blob basic usage

create

Blob object can be created by the constructor of Blob:
Blob(blobParts[, options])
Parameters:
blobParts : an array type, the array connected Blob object data constituting each item, each element in the array may be ArrayBuffer(二进制数据缓冲区), ArrayBufferView,Blob,DOMString. Or a mixture of other similar objects.
Options : Options, dictionary format type, you can specify the following two properties:

  • type, default value "", which represents the MIME type of the contents of the array will be put to the blob of.
  • endings, default is "transparent", comprising a line terminator specifies \nhow the string is written. It is one of two values: "native", represents the line endings will be changed to fit the host operating system, file system, line breaks; "transparent", said they would keep the blob saved in the same terminator.
    For chestnut:
    var data1 = "a";
    var data2 = "b";
    var data3 = "<div style='color:red;'>This is a blob</div>";
    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);  //输出:Blob {size: 1, type: ""}
    console.log(blob2);  //输出:Blob {size: 2, type: ""}
    console.log(blob3);  //输出:Blob {size: 44, type: ""}
    console.log(blob4);  //输出:Blob {size: 14, type: ""}
    console.log(blob5);  //输出:Blob {size: 15, type: ""}
    console.log(blob6);  //输出:Blob {size: 59, type: ""}

size representative of Blobthe number of bytes of data contained in objects. It is noted here, when the Blob create different strings and use common objects, blob4 use by JSON.stringifyconverting the object into a json string data4, blob5 data4 is used directly to create, size two objects 14 and 15, respectively. 14 of equal size blob4 be readily appreciated, as the result JSON.stringify (data4) is: "{"name":"abc"}", exactly 14 bytes (not including the outermost quotes). blob5 the size is equal to 15 how to calculate from? In fact, when you create a Blob object using ordinary objects, it is equivalent to calling the toString ordinary objects () method to get the string data, then create a Blob object. Therefore, blob5 stored data "[object Object]", 15 bytes (not including the outermost quotes).

slice method

Blob object slice has a method that returns a new Blobobject containing the Blob object to develop the source data range.
Parameter Description:

start: Alternatively, the representative Blobin the subscript denotes the first one will be will be copied into the new Blobbyte starting position. If the incoming is negative, then the offset will be calculated from the end of the data from back to front.

end: optional, represent Bloban index, the index corresponding to the byte-1 would be copied into the new Bloblast byte. If you pass a negative number, then the offset will be calculated from the end of the data from back to front.

contentType: Optional, to the new Blobendow a new document type. This will put its type attribute set to be passed in value. Its default value is a null string.
For chestnut:

    var data = "abcdef";
    var blob1 = new Blob([data]);
    var blob2 = blob1.slice(0,3);
    
    console.log(blob1);  //输出:Blob {size: 6, type: ""}
    console.log(blob2);  //输出:Blob {size: 3, type: ""}

The slice method by creating blob1 out from a new blob objects, size equal to 3.

Blob object can be added to the form, as used to upload data:

const content = '<a id="a"><b id="b">hey!</b></a>';
const blob = new Blob([content], {type: 'text/xml'});

formData.append('webmasterfile', blob);

Blob usage scenarios

Part uploading

As already mentioned, File inherit word Blob, so we can call the slice method for uploading large files to be fragmented. Code:

function uploadFile(file) {
  var chunkSize = 1024 * 1024; //每片1M大小
  var totalSize = file.size;
  var chunkQuantity = Math.ceil(totalSize/chunkSize); //分片总数
  var offset = 0; //偏移量

  var reader = new FileReader();
  reader.onload = function(e) {
    var xhr = new XMLHttpRequest();
    xhr.open("POST", url);
    xhr.overrideMineType("application/octet-stream");
    
    xhr.onreadstatechange = function() {
      if(xhr.readyState === 4 && xhr.status ===200) {
        ++offset;
        if(offset === chunkQuantity) {
          alerrt("上传完成");
        } else if(offset === chunckQuantity-1) {
          blob = file.slice(offset*chunkSize, totalSize);
          reader.readAsBinaryString(blob);
        } else {
          blob = file.slice(offset*chunkSize, (offset+1)*chunckSize);
          reader.readAsBinaryString(blob);
        }
      }else {
        alert("上传出错");
      }
    }

    if(xhr.sendAsBinary) {
      xhr.sendAsBinary(e.target.result);
    } else {
      xhr.send(e.target.result);
    }
  }
  var blob = file.slice(0, chunkSize);
  reader.readAsBinaryString(blob);
}

This code can also be further enriched, such as displaying the current upload progress, upload a plurality of parallel objects XMLHttpRequest object (sliced ​​data need to pass parameters to the server to obtain location) and the like.

Blob URL

Blob URL is a blob of agreements URL, its format is as follows:
blob:http://xxx
Blob URL can be URL.createObjectURL(blob)created. In most scenarios, we may like to use the same URL Http protocol was using Blob URL. There was a common scene: as the file was downloaded as a picture and address resource address.

  • Download file
<!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.getElementByTageName('a')[0];
      link.download = "file";
      link.href = URL.createObjectURL(blob);
    }
    window.onload = createDownloadFile;
  </script>
</head>

<body>
  <a>下载</a>
</body>

</html>

Click on the download button, your browser will have to download a file named file, the file contents must be: Blob Data. By Blob object, we can dynamically generate documents in front-end code to the browser download. Open the Chrome browser to debug window, you can see in the Elements label must generate the URL of Blob:
[Image upload failed ... (image-130a5a-1551669191720) ]

  • Picture resource address
    to create a Blob URL for the image file, assigned to the label:
<!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.getElementByTagName("img")[0];
      img.src = blob;
      img.onload = function(e) {
        URL.revokeObjectURL(this.src); //释放createObjectURL创建得对象
      }
    }
  </script>
</head>

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

</html>

imput the chosen picture will be displayed here:
[Image upload failed ... (image-c20d1f-1551669191720) ]
Meanwhile, in the Network tab bar can be found in this Blob URL may request information:
[Image upload failed ... ( image-fa2288-1551669191720)]
this information request and we usually use Http URLto obtain the picture was almost exactly the same.

window.URL.revokeObjectURL()

Each call createObjectURL () method will create a new URL object, even if you've been with the same objects created as a parameter. When these URL object is no longer needed, each object must call URL.revokeObjectURL () method to release. The browser will automatically release them when the document exit, but for best performance and memory usage, you should take the initiative to relieve them in a safe opportunity.
window.URL.revokeObjectURL(objectURL);

  • We can also use the Data URL Load picture resources:
<!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.getElementByTagName("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>

Data URL for all of us is not new, Web performance optimization have one measure: the small picture embedded in base64 encoded directly into the HTML file, the actual use of the Data URL is to get the picture data.


So Blob URL and Data URL What difference does it make?

  1. Blob URL length is generally too short, but Data URL because the data was stored directly in the base64-encoded images, often very long. When the show the big picture, using the Blob URL better.
  2. Blob URL can easily use the XMLHttpRequest data acquisition source, for example:
var blobUrl = URL.createObkectURL(new Blob(['Test'], {type: 'text/plain'}));
var xhr = new XMLHttpRequest();
//如果是指xhr.responseType = 'blob',将返回一个Blob对象,而不是文本;
//xhr.responseType = 'blob';
xhr.onload = function() {
  alert(xhr.responseText);
}
xhr.open('get', blobUrl);
xhr.send();

For Data URL, not all browsers support the acquisition of source data through XMLHttpRequest.

  1. Blob URL can only be applied in the current internal use , copy Blob URL into the address bar of your browser is unable to obtain the data. Data URL contrast, has a good portability, you can use any browser.

In addition to pictures can be used as a network address resources, Blob URL can also be used as a network address other resources, such as html file, json file, etc., in order to ensure that the browser can correctly parse the file type Blob URL returned, you need to create a Blob object when specifying the appropriate type:

//创建HTML文件的Blob URL
var data = "<div style='color:red;'This is a blob</div>";
var blob = new Blob([data], {type: 'text/html'}); // 'application/json'
var blobUrl = URL.createObjectURL(blob);

Guess you like

Origin www.cnblogs.com/cheng825/p/11694348.html