BLOB:Binary Large OBject,二進(jìn)制大文件,以字節(jié)數(shù)組的方式存儲(chǔ)。
Blob對(duì)象表示一個(gè)不可變的、原始數(shù)據(jù)類型的類文件對(duì)象。
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.
構(gòu)造函數(shù)
var aBlob = new Blob( array[, options])
// array可以為ArrayBuffer、ArrayBufferView、Blob、DOMStrings這些,或者他們的各種組合
// options: 包含type和ending。type表示內(nèi)容的MIME類型。
下圖為一典型BLob對(duì)象

Blob屬性
- size: Blob對(duì)象包含的字節(jié)數(shù)
- type: Blob對(duì)象內(nèi)部數(shù)據(jù)的MIME類型, 默認(rèn)為空
Blob是不能直接讀取內(nèi)容的,需要用到fileReader。
var reader = new FileReader();
reader.addEventListener("loadend", function() {
// reader.result contains the contents of blob as a typed array
});
reader.readAsArrayBuffer(aBlob);
應(yīng)用
AJAX
在POST請(qǐng)求時(shí):
XMLHttpRequest.send(body)
與fileReader相結(jié)合,在使用send()發(fā)送二進(jìn)制文件時(shí),一般會(huì)用Blob或者ArrayBuffer
具體實(shí)現(xiàn)如下:
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) 因?yàn)閟end是可以直接發(fā)送arrayBuffer的,這里只是說(shuō)明AJAX可以用Blob發(fā)送 數(shù)據(jù), 而且大部分時(shí)候都習(xí)慣用formdata或者是string
xhr.send(new Blob([reader.result]));
})
Blob和ArrayBuffer的區(qū)別
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中的介紹
對(duì)比ArrayBuffer vs Blob and XHR2
ArrayBuffer與Blob的相互轉(zhuǎn)化:stackoverflow