summary
- Blob: a blob object represents an immutable, raw data class file object. Its data can be read in text or binary format, or converted into ReadableStream for data operation.
- Arraybuffer: the arraybuffer object is used to represent a generic, fixed length raw binary data buffer.
- Buffer: the buffer object is from Nodejs and represents a fixed length byte sequence.
Diagram
Blob
Blob is used to support file operations.
The File object inherits from Blob, has all the properties and methods of Blob, and has its own unique properties and methods.
The File object is the FileList object returned after the user selects a File on an input element, or the DataTransfer object generated by free drag and drop operation, or the mozGetAsFile() API on HTMLCanvasElement.
grammar
var aBlob = new Blob( array, options ); var aFileParts = ['<a id="a"><b id="b">hey!</b></a>']; // An array containing DOMString var oMyBlob = new Blob(aFileParts, {type : 'text/html'}); // Get blob
- Array: an array composed of ArrayBuffer, ArrayBufferView, Blob, DOMString and other objects.
- options is an optional BlobPropertyBag dictionary, which may specify the following two properties:
– type, the default value is' ', which represents the MIME type of the array content to be put into the blob. (DOMStrings will be encoded as UTF-8)
– endings, the default value is "transparent", which is used to specify how the string containing the line terminator \ n is written. It is one of the following two values: "native", which means that the line terminator will be changed to a line feed suitable for the file system of the host operating system, or "transparent", which means that the terminator saved in the blob will remain unchanged
attribute
- Blob.size (read only): the size (in bytes) of the data contained in the blob object.
- Blob.type (read-only): a string indicating the MiME type contained in the blob object. Null if the type is unknown.
method
- slice: returns a new bloc object containing data within the specified range of the source bloc object.
- stream: returns a ReadableStream that can read blob content.
- text: returns a promise of USVString in UTF-8 format containing all contents.
- ArrayBuffer: returns the promise of an ArrayBuffer in binary format containing all the contents of the blob.
function
- File download: generate Blob URL through URL.createObjectURL(blob) and assign it to a.download attribute
- The picture shows that the Blob URL is generated through the URL.createObjectURL(blob) and assigned to the img.src attribute
- Resource segmented upload: split binary data into sub blob objects through blob.slice
- Local File reading: FileReader api can convert Blob or File objects into text, ArrayBuffer, Data URL, etc
Blob file download
Receive a Blob (File) object through the window.createObjectURL, convert it into a Blob URL, and then assign it to the a.download attribute. Click the a tag on the page to download the File.
<!-- html part --> <a id="h">Click here to download</a> <!-- js part --> <script> var blob = new Blob(["Hello World"]); var url = window.URL.createObjectURL(blob); var a = document.getElementById("h"); a.download = "helloworld.txt"; a.href = url; </script>
Blob realizes local picture display
<!-- html part --> <input type="file" id='f' /> <img id='img' style="width: 200px;height:200px;" /> <!-- js part --> <script> document.getElementById('f').addEventListener('change', function (e) { var file = this.files[0]; const img = document.getElementById('img'); const url = window.URL.createObjectURL(file); img.src = url; img.onload = function () { // Release a URL object previously created by calling URL.createObjectURL window.URL.revokeObjectURL(url); } }, false); </script>
Blob reads local file contents
If you want to read Blob objects or file objects and convert them to data in other formats, you can operate with the API of FileReader object
- FileReader.readAsText(Blob): convert Blob to text string
- FileReader.readAsArrayBuffer(Blob): convert Blob to ArrayBuffer format data
- FileReader.readAsDataURL(): convert Blob to Base64 format Data URL
ArrayBuffer
ArrayBuffer is a byte array. The contents of ArrayBuffer cannot be operated directly. They can only be operated through type array objects or DataView objects. They will represent the data of the buffer in specific formats and read and write the contents of the buffer through these formats.
Generation background
Related to WebGL project, the traditional text format communication requires binary formatting of information. In order to improve the communication speed between browser and graphics card, the way of directly transmitting binary data is adopted, and the communication speed is greatly improved.
grammar
new ArrayBuffer(length) // Returns an ArrayBuffer object of the specified size
- length: the size of the ArrayBuffer to be created, in bytes.
attribute
- byteLength: indicates the memory byte length occupied by the current instance (read-only)
const buffer = new ArrayBuffer(32); buffer.byteLenfth; // 32
method
- isView: returns true if the parameter is a view instance of ArrayBuffer, such as a type array object or DataView object; otherwise, returns false
- slice(begin,end): returns a new ArrayBuffer containing byte copies from begin (including) to end (excluding)
function
Read: convert the file into ArrayBuffer data through FileReader
Write: operate through TypedArray or DataView objects
Read local data through ArrayBuffer
document.getElementById('f').addEventListener('change', function (e) { const file = this.files[0]; const fileReader = new FileReader(); fileReader.onload = function () { const result = fileReader.result; console.log(result) } fileReader.readAsArrayBuffer(file); }, false);
Write to ArrayBuffer through TypeArray
const typedArray1 = new Int8Array(8); typedArray1[0] = 32; const typedArray2 = new Int8Array(typedArray1); typedArray2[1] = 42; console.log(typedArray1); // output: Int8Array [32, 0, 0, 0, 0, 0, 0, 0] console.log(typedArray2); // output: Int8Array [32, 42, 0, 0, 0, 0, 0, 0]
Write to ArrayBuffer through DataView
const buffer = new ArrayBuffer(16); const view = new DataView(buffer); view.setInt8(2, 42); console.log(view.getInt8(2)); // Output: 42
Differences from native arrays
length | Storage place | Operation data method | read-only | |
---|---|---|---|---|
ArrayBuffer | fixed | Stack | nothing | √ |
Array | It can be increased or decreased freely | heap | push/pop | × |
Buffer
The object provided by Nodejs does not exist in the front end. Generally used for IO operation. For example, when the front-end requests data, the received front-end data can be integrated through the Buffer.
Work flow chart
function
node receives request data
// Node end const app = new Koa(); app.use(async (ctx, next) => { if (ctx.path === '/ajax') { const chunks = []; const req = ctx.req; req.on('data', buf => { chunks.push(buf); }) req.on('end', () => { let buffer = Buffer.concat(chunks); console.log(buffer.toString()) }) } }); app.listen(3000) // request const xhr = new XMLHttpRequest(); xhr.open("POST", "ajax", true); xhr.setRequestHeader('Content-Type', 'text/plain') xhr.send("asdfgghjhjkttyuerttwerweqr");