ArrayBuffer object, Blob object

ArrayBuffer Object

The ArrayBuffer object represents a piece of binary data, which is used to simulate the data in the memory. Through this object, JavaScript can read and write binary data. This object can be seen as an expression of memory data.

This object is only written into the standard in ES6, and it is not used in ordinary web programming. In order to complete the tutorial system, only a brief introduction is provided below. For detailed introduction, please see the chapters in "Introduction to ES6 Standards".

The browser natively provides the ArrayBuffer() constructor to generate examples. It accepts an integer as a parameter, which indicates how many bytes this piece of binary data occupies.

var buffer = new ArrayBuffer(8);

In the above code, the instance object buffer occupies 8 bytes.

The ArrayBuffer object has an instance attribute byteLength, which represents the memory length (in bytes) occupied by the current instance.

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

The ArrayBuffer object has an instance method slice(), which is used to copy part of the memory. It accepts two integer parameters, which respectively represent the start position of the copy (starting from 0) and the end position (the end position is not included when copying). If the second parameter is omitted, it means that the copy has been copied to the end.

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

The above code means to copy the original instance.

Blob object

Introduction

The Blob object represents the data content of a binary file. For example, the content of a picture file can be read and written through the Blob object. It is usually used to read and write files, and its name is the abbreviation of Binary Large Object. The difference between it and ArrayBuffer is that it is used to manipulate binary files, while ArrayBuffer is used to manipulate memory.

The browser natively provides the Blob() constructor to generate instance objects.

new Blob(array [, options])

The Blob constructor accepts two parameters. The first parameter is an array, and the members are strings or binary objects, representing the content of the newly generated Blob instance object; the second parameter is optional and is a configuration object, currently there is only one attribute type, it The value of is a string representing the MIME type of the data, and the default is an empty string.

var htmlFragment = ['<a id="a"><b id="b">hey!</b></a>'];
var myBlob = new Blob(htmlFragment, { type: "text/html" });

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, Blob saves JSON data.

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

Instance attributes and instance methods

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

var htmlFragment = ['<a id="a"><b id="b">hey!</b></a>'];
var myBlob = new Blob(htmlFragment, { type: "text/html" });

myBlob.size; // 32
myBlob.type; // "text/html"

Blob has an instance method slice, which is used to copy the original data, and returns a Blob instance.

myBlob.slice(start, end, contentType);

The slice method has three parameters, all of which are optional. They are the starting byte position (the default is 0), the ending byte position (the default is the value of the size attribute, the position itself will not be included in the copied data), and the data type of the new instance ( The default is an empty string).

Get file information

The file selector <input type="file"> is used to allow users to select files. For security reasons, browsers do not allow scripts to set the value attribute of this control by themselves, that is, the file must be manually selected by the user, and cannot be specified by the script. Once the user selects the file, the script can read the file.

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

// 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, // file name without path
      f.size, // File size, Blob instance attributes
      f.type, // File type, Blob instance attribute
      f.lastModifiedDate // The last modification time of the file
    );
  }
}

In addition to the file selector, the dataTransfer.files of the drag and drop API also returns a FileList object, and its members are therefore also File instance objects.

download file

In an AJAX request, if the responseType attribute is specified as blob, the downloaded file is 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);
}

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

Generate URL

Browsers allow the use of the URL.createObjectURL() method to generate a temporary URL for the Blob object for use by certain APIs. This URL starts with blob://, indicating that it corresponds to a Blob object. After the protocol header is an identifier that uniquely corresponds to the Blob object in the memory. This is different from data://URL (URL contains actual data) and file://URL (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);
    };
  }
};

The above code generates a URL for the drag-and-drop image files and generates their thumbnails, so that the user can preview the selected files.

The browser processes Blob URLs just like ordinary URLs. If the Blob object does not exist, it returns a 404 status code; if a cross-domain request is made, it returns a 403 status code. The Blob URL is only valid for GET requests. If the request is successful, a 200 status code will be returned. Since the Blob URL is a normal URL, it can be downloaded.

Read file

After obtaining the Blob object, you can read the content of the Blob object, that is, the file content, through the FileReader object.

The FileReader object provides four methods to deal with Blob objects. Blob objects are passed into these methods as parameters, and then returned in the specified format.

-FileReader.readAsText(): To return the text, you need to specify the text encoding, the default is UTF-8. -FileReader.readAsArrayBuffer(): returns an ArrayBuffer object.

  • FileReader.readAsDataURL():返回 Data URL。 -FileReader.readAsBinaryString(): returns the original binary string.

The following is an example of the FileReader.readAsText() method, which is used to read a text file.

// 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);
  };
}

In the above code, by specifying the onload monitoring function of the FileReader instance object, the file content is obtained on the result property of the instance.

The following is an example of the FileReader.readAsArrayBuffer() method for reading a binary file.

// HTML code is as follows
// <input type="file" onchange="typefile(this.files[0])"></input>
function typefile(file) {
  // The four bytes at the beginning of the file generate a Blob object
  var slice = file.slice(0, 4);
  var reader = new FileReader();
  // read these 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);
    // According to the first four bytes of the file, determine its type
    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);
  };
}