BLOB:Binary Large OBject,二进制大文件,以字节数组的方式存储。
Blob对象表示一个不可变的、原始数据类型的类文件对象。
A Blob object represents a file-like object of immutable, raw data. Blobs represent data that isn't necessarily in a JavaScript-native format. The File interface is based on Blob, inheriting blob functionality and expanding it to support files on the user's system.
构造函数
var aBlob = new Blob( array[, options])
// array可以为ArrayBuffer、ArrayBufferView、Blob、DOMStrings这些,或者他们的各种组合
// options: 包含type和ending。type表示内容的MIME类型。
下图为一典型BLob对象
Blob属性
- size: Blob对象包含的字节数
- type: Blob对象内部数据的MIME类型, 默认为空
Blob是不能直接读取内容的,需要用到fileReader。
var reader = new FileReader();
reader.addEventListener("loadend", function() {
// reader.result contains the contents of blob as a typed array
});
reader.readAsArrayBuffer(aBlob);
应用
AJAX
在POST
请求时:
XMLHttpRequest.send(body)
与fileReader相结合,在使用send()发送二进制文件时,一般会用Blob或者ArrayBuffer
具体实现如下:
var fileInput = document.querySelector('input[type=file]')
var file = fileInput.files[0]
var reader = new FileReader()
var xhr = new XMLHttpRequest();
xhr.open("POST", '/server', true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {//Call a function when the state changes.
if(xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) {
// do something here
}
}
reader.readAsArrayBuffer(file)
reader.addEventListener('load', function () {
// xhr.send(reader.result) 因为send是可以直接发送arrayBuffer的,这里只是说明AJAX可以用Blob发送 数据, 而且大部分时候都习惯用formdata或者是string
xhr.send(new Blob([reader.result]));
})
Blob和ArrayBuffer的区别
You would use an ArrayBuffer when you need a typed array because you intend to work with the data, and a blob when you just need the data of the file
参考文档:
Blob在MDN中的介绍
Blob在W3C中的介绍
对比ArrayBuffer vs Blob and XHR2
ArrayBuffer与Blob的相互转化:stackoverflow