This is the fifth day of my participation in the August Wen Challenge.More challenges in August

What is a Blob A Blob is a JavaScript object type. Blob objects store large amounts of binary data, and the familiar File object is inherited from blobs, as are the size and type attributes. How to Create a Blob Object To create a Blob object you need to pass two parameters, one is a data sequence, which can be a value of any format, and the other is an object with two properties, {type: MIME type, Hamed: Determine the data format of the first parameter. The value can be “transparent” or “native” (transparent is the default value, and native is converted by operating system). }

Blob = new blob ([" data "], {type:'text/plain'}) var reader = new FileReader(); // Create a reader object. ReadAsText (blob); Reader.onload = function () {console.log(read.result); // Get data from result}Copy the code

The attribute Blob has two attributes size, Type, and Hamed

  • Blob.size Size of the data contained in the Blob object (in bytes).
  • Blob.type A string, such as the type of string or file, that indicates the MIME type of the data contained in the Blob object. If the type is unknown, the value is an empty string
  • endings

The default value is “transparent”, which specifies how strings containing line terminator \n are 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.

methods

  • Blob.close() closes the Blob object so that the underlying resources can be freed.
  • Blob.slice([start[, end[, contentType]]]) returns a new Blob object containing the data in the range specified in the source Blob object. This is essentially slicing up the data in the BLOB, and we need to use this method when uploading files in fragments.

Blob. Slice method

A Blob object has a slice method that returns a new Blob object containing the specified range of data from the source Blob object. Parameter Description:

parameter The values describe
start optional On behalf ofBlobThe starting position of the byte of. If a negative number is passed in, the offset will be calculated from the end of the data to the front.
end optional On behalf ofBlobThe starting position of the byte of. If a negative number is passed in, the offset will be calculated from the end of the data to the front.
contentType optional For the newBlobGive 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.5);
    
    console.log(blob1);  Blob {size: 6, type: ""}
    console.log(blob2);  Blob {size: 5, type: ""}
Copy the code

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

Blob objects can be added to forms for use as upload data:

const content = 'hey! ';
const blob = new Blob([content], {type: 'text/xml'});
formData.append('webmasterfile', blob); -- Generally used as an uploaded fileCopy the code

Blob usage scenarios

Shard to upload

First of all, let’s talk about sharding upload. When we upload files, the size of the files uploaded to the server will not be very large due to the limitation of the server. At this time, we need to cut the files to be uploaded and upload them to the server separately.

To do this, we need to solve two problems:

  • How do you cut it?
  • How do I know the current transmission progress?

Since File objects inherit from Blob objects, File objects also have the slice method, which can be used to slice any File.

Segmentation is just a matter of sizing, bit by bit transmission

var size = 1024 * 1024; // Each file slice size is set to 1MB.
var blob = document.getElementById("file").files[0];
var slices = Math.ceil(blob.size / size);
var blobs = [];
slices.forEach(function(item, index) {
    blobs.push(blob.slice(index,index + 1));
});
Copy the code

The specific split upload is as follows

function uploadFile(file) {
  var chunkSize = 1024 * 1024; // Each piece is 1M in size
  var totalSize = file.size;
  var chunkQuantity = Math.ceil(totalSize/chunkSize); // Total number of fragments
  var offset = 0; / / the offset

  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("Upload completed");
        } 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("Upload error"); }}if(xhr.sendAsBinary) {
      xhr.sendAsBinary(e.target.result);
    } else{ xhr.send(e.target.result); }}var blob = file.slice(0, chunkSize);
  reader.readAsBinaryString(blob);
}
Copy the code

Blob URL for download

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.getElementByTageName('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 see the generated Blob URL under the Elements TAB

  • Image resource address Creates a Blob URL for the image file and assigns it to the tag:
<! 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); </script> </head> <body> <input type="flie" Accept ="image/*" onchange="handleFile(this)"  <br/> <img style="width:200px; height:200px;" > </body> </html>Copy the code

The image selected in imput will be displayed here

At the same time, the request information for the Blob URL can be found in the Network TAB

This request information is almost identical to what we would normally get for an image using an Http URL.

window.URL.revokeObjectURL()

Every time the createObjectURL() method is called, a new URL object is created, even if you already created it with the same object as an argument. When these URL objects are no longer needed, each object must be freed by calling the url.revokeobjecturl () method. Browsers automatically release documents when they exit, but for best performance and memory usage, you should actively release them when it’s safe to do so. window.URL.revokeObjectURL(objectURL);

  • 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.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>Copy the code

Data URL is not unfamiliar to everyone. There is a measure of Web performance optimization: embedding small pictures in HTML files directly with Base64 encoding, which actually uses Data URL to obtain picture Data.

Finally, what’s the difference between Blob urls and Data urls?

  1. Blob urls tend to be short in length, but Data urls tend to be long because they store base64 encoded Data directly from images. When displaying large images, using Blob urls is preferable.
  2. Blob urls make it easy to retrieve source data using XMLHttpRequest, for example:
var blobUrl = URL.createObkectURL(new Blob(['Test'] and {type: 'text/plain'}));
var xhr = new XMLHttpRequest();
// if xhr.responseType = 'blob', a blob object is returned instead of text;
//xhr.responseType = 'blob';
xhr.onload = function() {
  alert(xhr.responseText);
}
xhr.open('get', blobUrl);
xhr.send();
Copy the code

For Data urls, not all browsers support XMLHttpRequest to retrieve the source Data.

  1. Blob urls are only used within the current application, and copying Blob urls to the browser address bar does not retrieve 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:

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);Copy the code