This is the third day of my participation in the August More Text Challenge

ArrayBuffer object, Blob object

ArrayBuffer object

An ArrayBuffer represents a piece of binary data that is used to simulate data in memory. From this object, JavaScript can read and write binary data. This object can be thought of as an expression of memory data.

The browser natively provides the ArrayBuffer() constructor, which is used to generate instances. It takes an integer as an argument to indicate how many bytes the binary data takes up.

var buffer = new ArrayBuffer(8);
Copy the code

In the above code, the instance object buffer takes up 8 bytes.

The ArrayBuffer object has the instance property byteLength, which represents the length of memory (in bytes) currently occupied by the instance.

var buffer = new ArrayBuffer(8);
buffer.byteLength / / 8
Copy the code

The ArrayBuffer object has the instance method Slice (), which is used to copy a portion of memory. It takes two integer arguments indicating the start of the copy (starting at 0) and the end (not included at the time of the copy), or until the end if the second argument is omitted.

var buf1 = new ArrayBuffer(8);
var buf2 = buf1.slice(0);
Copy the code

The above code indicates copying the original instance.

A Blob object

Introduction to the

Blob objects represent the data contents of a binary file, such as the contents of an image file, which can be read and written from Blob objects. It is commonly used to read and write files, and its name is short for Binary Large Object. It differs from ArrayBuffer in that it is used to manipulate binary files, whereas ArrayBuffer is used to manipulate memory.

Browsers natively provide the Blob() constructor, which generates instance objects.

new Blob(array [, options])
Copy the code

The Blob constructor takes two arguments. The first argument is an array whose members are strings or binary objects representing the contents of the newly generated Blob instance object. The second argument, which is optional, is a configuration object that currently has only one property, Type, whose value is a string representing the MIME type of the data. The default is an empty string.

var htmlFragment = ['hey! '];
var myBlob = new Blob(htmlFragment, {type : 'text/html'});
Copy the code

In the above code, the instance object myBlob contains strings. When the instance is generated, the data type is specified as text/ HTML.

Here is another example where a Blob holds JSON data.

var obj = { hello: 'world' };
var blob = new Blob([ JSON.stringify(obj) ], {type : 'application/json'});
Copy the code

Instance properties and instance methods

Blob has two instance attributes size and type that return the size and type of the data, respectively.

var htmlFragment = ['hey! '];
var myBlob = new Blob(htmlFragment, {type : 'text/html'});

myBlob.size / / 32
myBlob.type // "text/html"
Copy the code

Blob has an instance method slice that copies the original data and returns an instance of the Blob.

myBlob.slice(start, end, contentType)
Copy the code

The Slice method takes three parameters, all of which are optional. These, in turn, are the starting byte position (default: 0), the ending byte position (default: the value of the size property, which itself will not be included in the copied data), and the data type of the new instance (default: empty string).

Obtaining File Information

The file selector is used to allow the user to select a file. For security reasons, the browser does not allow the script to set the value property of the control itself, that is, the file must be manually selected, not specified by the script. Once the user selects the file, the script can read it.

The File selector returns a FileList object, which is an array-like member. Each member is a File instance object. The File instance object is a special Blob instance with the name and lastModifiedDate attributes added.

// The HTML code is as follows
// <input type="file" accept="image/*" multiple onchange="fileinfo(this.files)"/>

function fileinfo(files) {
  for (var i = 0; i < files.length; i++) {
    var f = files[i];
    console.log(
      f.name, // The file name does not contain the path
      f.size, // File size, Blob instance properties
      f.type, // File type, Blob instance property
      f.lastModifiedDate // When the file was last modified); }}Copy the code

In addition to the File selector, the drag-and-drop API’s datatransfer. files returns a FileList object, whose members are therefore File instance objects.

The download file

If you specify the responseType property as BLOb when making an AJAX request, you download a BLOB object.

function getBlob(url, callback) {
  var xhr = new XMLHttpRequest();
  xhr.open('GET', url);
  xhr.responseType = 'blob';
  xhr.onload = function () {
    callback(xhr.response);
  }
  xhr.send(null);
}
Copy the code

In the code above, xhr.response gets a Blob object.

To generate the URL

The browser allows you to use the url.createObjecturl () method to generate a temporary URL for the Blob object for use by some apis. The URL begins with blob://, indicating a BLOB object, followed by an identifier that uniquely identifies the bloB object in memory. This is different from data://URL (which contains actual data) and file://URL (which is a file in the local file system).

var droptarget = document.getElementById('droptarget');

droptarget.ondrop = function (e) {
  var files = e.dataTransfer.files;
  for (var i = 0; i < files.length; i++) {
    var type = files[i].type;
    if (type.substring(0.6)! = ='image/')
      continue;
    var img = document.createElement('img');
    img.src = URL.createObjectURL(files[i]);
    img.onload = function () {
      this.width = 100;
      document.body.appendChild(this);
      URL.revokeObjectURL(this.src); }}}Copy the code

The code above allows the user to preview the selected file by generating a URL for the drag-and-drop image files, producing their thumbnails.

Browsers handle Blob urls just like normal urls, returning a 404 status code if the Blob object does not exist; If cross-domain request, return 403 status code. The Blob URL is valid only for GET requests and returns a 200 status code if the request is successful. Because Blob urls are normal urls, they can be downloaded.

Read the file

Once you have the Blob object, you can read the contents of the Blob object, the contents of the file, through the FileReader object.

The FileReader object provides four methods for handling Blob objects. Blob objects are passed in as arguments to these methods and returned in the specified format.

  • FileReader.readAsText(): Returns text. The text encoding must be specified. The default value is UTF-8.
  • FileReader.readAsArrayBuffer(): Returns an ArrayBuffer object.
  • FileReader.readAsDataURL(): Returns the Data URL.
  • FileReader.readAsBinaryString(): Returns the original binary string.

Here is an example of the filereader.readastext () method to read text files.

// The HTML code is as follows
// <input type="file" onchange="readfile(this.files[0])"></input>
// <pre id="output"></pre>
function readfile(f) {
  var reader = new FileReader();
  reader.readAsText(f);
  reader.onload = function () {
    var text = reader.result;
    var out = document.getElementById('output');
    out.innerHTML = ' ';
    out.appendChild(document.createTextNode(text));
  }
  reader.onerror = function(e) {
    console.log('Error', e);
  };
}
Copy the code

In the above code, we get the file contents on the result property of the FileReader instance by specifying the onload listener of the FileReader instance.

. Below is the FileReader readAsArrayBuffer example () method, is used to read binary file.

// The HTML code is as follows
// <input type="file" onchange="typefile(this.files[0])"></input>
function typefile(file) {
  // The first four bytes of the file generate a Blob object
  var slice = file.slice(0.4);
  var reader = new FileReader();
  // Read the four bytes
  reader.readAsArrayBuffer(slice);
  reader.onload = function (e) {
    var buffer = reader.result;
    // Treat the contents of these four bytes as a 32-bit integer
    var view = new DataView(buffer);
    var magic = view.getUint32(0.false);
    // Determine the type of the file based on the first four bytes
    switch(magic) {
      case 0x89504E47: file.verified_type = 'image/png'; break;
      case 0x47494638: file.verified_type = 'image/gif'; break;
      case 0x25504446: file.verified_type = 'application/pdf'; break;
      case 0x504b0304: file.verified_type = 'application/zip'; break;
    }
    console.log(file.name, file.verified_type);
  };
}
Copy the code