JavaScript 有两种主要的方式来表示浏览器中的二进制数据。ArrayBuffers/TypedArrays 包含可以直接操作的可变(尽管仍然是固定长度)二进制数据。Blob 包含只能通过异步文件接口访问的不可变二进制数据。
# 将 Blob 转换为 ArrayBuffer(异步方式)
var blob = new Blob(["\x01\x02\x03\x04"]), | |
fileReader = new FileReader(), | |
array; | |
fileReader.onload = function () { | |
array = this.result; | |
console.log("Array contains", array.byteLength, "bytes."); | |
}; | |
fileReader.readAsArrayBuffer(blob); |
6
# 使用 Promise 将 Blob 转换为 ArrayBuffer(异步方式)
var blob = new Blob(["\x01\x02\x03\x04"]); | |
var arrayPromise = new Promise(function (resolve) { | |
var reader = new FileReader(); | |
reader.onloadend = function () { | |
resolve(reader.result); | |
}; | |
reader.readAsArrayBuffer(blob); | |
}); | |
arrayPromise.then(function (array) { | |
console.log("Array contains", array.byteLength, "bytes."); | |
}); |
# 将 ArrayBuffer 或 TypedArray 转换为 Blob
var array = new Uint8Array([0x04, 0x06, 0x07, 0x08]); | |
var blob = new Blob([array]); |
参考:
https://developer.mozilla.org/en-US/docs/Web/API/Blob
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer
https://es6.ruanyifeng.com/#docs/arraybuffer#ArrayBuffer-%E5%AF%B9%E8%B1%A1