This article was first published on my [Personal blog] for more rich front-end learning materials, check out my Github: Leo-javascript covers data structures and algorithms, HTTP, Hybrid, interview questions, React, Angular, TypeScript, Webpack, and more. Click a Star not to get lost ~
ArrayBuffer and Blob objects are common in file upload operations (e.g. image upload previews).
So this article will introduce both in depth with you.
ArrayBuffer object
The ArrayBuffer object was incorporated into the formal ECMAScript specification in ES6 and is an interface for JavaScript to manipulate binary data. An ArrayBuffer is an array syntax that processes binary data, also known as binary arrays.
TypedArray view and DataView are also introduced in this article. For details, see “Introduction to ArrayBuffer” in ECMAScript 6 by Ruan Yifeng.
1. Concept introduction
An ArrayBuffer represents a chunk of memory that stores binary data. It cannot be read or written directly, but can only be read or written through views (TypedArray and DataView views) that interpret binary data in a specified format.
For TypedArray views and DataView views, please refer to the introduction to ArrayBuffer in ECMAScript 6 by Yifeng Ruan.
2. Object usage
The browser natively provides the ArrayBuffer() constructor, which is used to generate instances.
Parameters:
- Integer: indicates the length of bytes occupied by binary data.
The return value:
- A specified size
ArrayBuffer
Object whose content is initialized to 0.
const buffer = new ArrayBuffer(32);
Copy the code
The above code indicates that the instance object buffer occupies 32 bytes.
3. instance properties and methods
The ArrayBuffer object has the instance property byteLength, which represents the length of memory (in bytes) occupied by the current instance and cannot be changed once created (read only) :
const buffer = new ArrayBuffer(32);
buffer.byteLength; / / 32
Copy the code
The ArrayBuffer object has the instance method Slice (), which is used to copy a portion of memory.
The parameters are as follows:
-
Start, an integer, indicates the location where replication starts. The value starts from 0 by default.
-
End, an integer, indicating the end of the replication (excluding the end position). If omitted, copy to end.
const buffer = new ArrayBuffer(32);
const buffer2 = buffer.slice(0);
Copy the code
4. The compatibility
Image from MDN
Blob objects
1. Concept introduction
Blob: Binary Large Object.
Blob objects represent the data contents of a binary file and are commonly used to read and write files, such as the contents of a picture file.
Differences from ArrayBuffer:
Blob
For manipulatingBinary fileArrayBuffer
For manipulatingmemory
2. Object usage
Browsers natively provide the Blob() constructor to generate instances.
The content of a Blob consists of a concatenation of values given in an array of parameters.
const leoBlob = new Blob(array [, options]);
Copy the code
Parameters:
array
, mandatory, the members are strings or binary objects representing the contents of the newly generated Blob instance object;
The member can be an Array of objects such as ArrayBuffer, ArrayBufferView, Blob, DOMString, etc., or a mixture of similar objects that will be put into the Blob. DOMStrings will be encoded to UTF-8.
options
Optional, is a configuration object. This section describes common propertiestype
Represents the MIME type of the data, default empty string;
Options currently have two attributes: Type and Hamed.
Hamid specifies how the string containing the line end character \n is written, the default value being transparent. It has only two values: native (which means that the line terminator will be changed to a newline suitable for the host operating system file system) and transparent (which means that the end character saved in the BLOb will be left unchanged).
Use cases:
const leoHtmlFragment = [' Hey Leo! ']; // An array containing DOMString
const leoBlob = new Blob(leoHtmlFragment, {type : 'text/html'}); / / get a blob
Copy the code
In this code, the instance object leoBlob contains a string. Specify the data type as text/ HTML when the instance is generated.
You can also use blobs to store JSON data:
const obj = { hello: 'leo' };
const blob = new Blob([ JSON.stringify(obj) ], {type : 'application/json'});
Copy the code
3. instance properties and methods
A Blob has two instance attributes:
-
Size: indicates the file size, in bytes.
-
Type: indicates the MIME type of the file. If the type cannot be determined, an empty string is returned.
const leoHtmlFragment = [' Hey Leo! ']; // An array containing DOMString
const leoBlob = new Blob(leoHtmlFragment, {type : 'text/html'}); / / get a blob
leoBlob.size; / / 38
leoBlob.type; // "text/html"
Copy the code
Blob instance methods:
clice
The: method is used to create an include sourceBlob
Is new for data in the specified byte rangeBlob
Object.
const newBlob = oldBlob.slice([start [, end [, contentType]]])
Copy the code
Contains three parameters:
Start, optional, starting byte position, default 0;
End, optional, the end byte position, the default size property value, does not include this position;
ContentType, optional, the data type of the new instance (default is empty string);
4. The compatibility
Image from MDN
5. Actual cases
5.1 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. This object is an array-like object. Each member is a File instance object. The File instance object is a special Blob instance with the name and lastModifiedDate attributes added.
Datatransfer. files, which also includes the drag-and-drop API, also returns a FileList object whose members are File instance objects.
// The HTML code is as follows
// <input type="file" accept="image/*" multiple onchange="fileinfo(this.files)"/>
function fileinfo(files) {
for (let i = 0; i < files.length; i++) {
let 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
5.2 Downloading Files
In an AJAX request, you can download a BLOB object by specifying the responseType property as BLOb.
function getBlob(url, callback) {
const xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.onload = function () {
callback(xhr.response);
}
xhr.send(null);
}
Copy the code
Xhr.response then gets a Blob object.
5.3 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.
As a URL for image preview.
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).
const droptarget = document.getElementById('droptarget');
droptarget.ondrop = function (e) {
const files = e.dataTransfer.files;
for (let i = 0; i < files.length; i++) {
let type = files[i].type;
if (type.substring(0.6)! = ='image/')
continue;
let 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
In the code, generate a URL for the drag-and-drop image file as a thumbnail of the preview.
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.
5.4 Reading Files
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. The Blob object is passed in as a parameter 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) {
let reader = new FileReader();
reader.readAsText(f);
reader.onload = function () {
let text = reader.result;
let out = document.getElementById('output');
out.innerHTML = ' ';
out.appendChild(document.createTextNode(text));
}
reader.onerror = function(e) {
console.log('Error', e);
};
}
Copy the code
. 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
let slice = file.slice(0.4);
let reader = new FileReader();
// Read the four bytes
reader.readAsArrayBuffer(slice);
reader.onload = function (e) {
let buffer = reader.result;
// Treat the contents of these four bytes as a 32-bit integer
let view = new DataView(buffer);
let 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
Iii. Reference materials
- ArrayBuffer objects, Blob objects
- ECMAScript 6 Getting Started with ArrayBuffer
Four, about me
This article was first published on pingan8787 personal blog, please keep personal introduction if necessary.
Author | Ping-an wang |
---|---|
[email protected] | |
Blog posts | www.pingan8787.com |
pingan8787 | |
Daily Article recommendations | Github.com/pingan8787/… |
ES small volumes | js.pingan8787.com |