简体   繁体   English

如何从 Blob 到 ArrayBuffer

[英]How to go from Blob to ArrayBuffer

I was studying Blobs, and I noticed that when you have an ArrayBuffer, you can easily convert this to a Blob as follows:我正在研究 Blob,我注意到当你有一个 ArrayBuffer 时,你可以很容易地将它转换为一个 Blob,如下所示:

var dataView = new DataView(arrayBuffer);
var blob = new Blob([dataView], { type: mimeString });

The question I have now is, is it possible to go from a Blob to an ArrayBuffer?我现在的问题是,是否可以从 Blob 转到 ArrayBuffer?

You can use FileReader to read the Blob as an ArrayBuffer .您可以使用FileReaderBlob作为ArrayBuffer读取。

Here's a short example:这是一个简短的例子:

var arrayBuffer;
var fileReader = new FileReader();
fileReader.onload = function(event) {
    arrayBuffer = event.target.result;
};
fileReader.readAsArrayBuffer(blob);

Here's a longer example:这是一个更长的例子:

// ArrayBuffer -> Blob
var uint8Array  = new Uint8Array([1, 2, 3]);
var arrayBuffer = uint8Array.buffer;
var blob        = new Blob([arrayBuffer]);

// Blob -> ArrayBuffer
var uint8ArrayNew  = null;
var arrayBufferNew = null;
var fileReader     = new FileReader();
fileReader.onload  = function(event) {
    arrayBufferNew = event.target.result;
    uint8ArrayNew  = new Uint8Array(arrayBufferNew);

    // warn if read values are not the same as the original values
    // arrayEqual from: http://stackoverflow.com/questions/3115982/how-to-check-javascript-array-equals
    function arrayEqual(a, b) { return !(a<b || b<a); };
    if (arrayBufferNew.byteLength !== arrayBuffer.byteLength) // should be 3
        console.warn("ArrayBuffer byteLength does not match");
    if (arrayEqual(uint8ArrayNew, uint8Array) !== true) // should be [1,2,3]
        console.warn("Uint8Array does not match");
};
fileReader.readAsArrayBuffer(blob);
fileReader.result; // also accessible this way once the blob has been read

This was tested out in the console of Chrome 27—69, Firefox 20—60, and Safari 6—11.这在 Chrome 27-69、Firefox 20-60 和 Safari 6-11 的控制台中进行了测试。

Here's also a live demonstration which you can play with: https://jsfiddle.net/potatosalad/FbaM6/这里还有一个你可以玩的现场演示: https : //jsfiddle.net/potatosalad/FbaM6/

Update 2018-06-23: Thanks to Klaus Klein for the tip about event.target.result versus this.result 2018 年 6 月 23 日更新:感谢 Klaus Klein 提供有关event.target.resultthis.result的提示

Reference:参考:

TheResponse API consumes a (immutable) Blob from which the data can be retrieved in several ways. Response API 使用一个(不可变的) Blob ,可以通过多种方式从中检索数据。 The OP only asked for ArrayBuffer , and here's a demonstration of it. OP只要求ArrayBuffer ,这是它的演示。

var blob = GetABlobSomehow();

// NOTE: you will need to wrap this up in a async block first.
/* Use the await keyword to wait for the Promise to resolve */
await new Response(blob).arrayBuffer();   //=> <ArrayBuffer>

alternatively you could use this:或者你可以使用这个:

new Response(blob).arrayBuffer()
.then(/* <function> */);

Note: This API isn't compatible with older ( ancient ) browsers so take a look to the Browser Compatibility Table to be on the safe side ;)注意:API与较旧的(古老的)浏览器不兼容,因此请查看浏览器兼容性表以确保安全;)

Or you can use the fetch API或者你可以使用 fetch API

fetch(URL.createObjectURL(myBlob)).then(res => res.arrayBuffer())

I don't know what the performance difference is, and this will show up on your network tab in DevTools as well.我不知道性能差异是什么,这也会显示在 DevTools 的网络选项卡上。

Just to complement Mr @potatosalad answer.只是为了补充@potatosalad 先生的回答。

You don't actually need to access the function scope to get the result on the onload callback, you can freely do the following on the event parameter:您实际上不需要访问函数作用域来获取onload回调的结果,您可以自由地对event参数执行以下操作:

var arrayBuffer;
var fileReader = new FileReader();
fileReader.onload = function(event) {
    arrayBuffer = event.target.result;
};
fileReader.readAsArrayBuffer(blob);

Why this is better?为什么这样更好? Because then we may use arrow function without losing the context因为那样我们就可以在不丢失上下文的情况下使用箭头函数

var fileReader = new FileReader();
fileReader.onload = (event) => {
    this.externalScopeVariable = event.target.result;
};
fileReader.readAsArrayBuffer(blob);

There is now (Chrome 76+ & FF 69+) a Blob.prototype.arrayBuffer() method which will return a Promise resolving with an ArrayBuffer representing the Blob's data. 现在(Chrome 76+ 和 FF 69+)有一个Blob.prototype.arrayBuffer()方法,它会返回一个 Promise ,用一个 ArrayBuffer 表示 Blob 的数据。

 (async () => { const blob = new Blob(['hello']); const buf = await blob.arrayBuffer(); console.log( buf.byteLength ); // 5 })();

await blob.arrayBuffer() is good. await blob.arrayBuffer()很好。

The problem is when iOS / Safari support is needed.. for that one would need this :问题是当需要 iOS / Safari 支持时......因为那个人需要这个

Blob.prototype.arrayBuffer ??=function(){ return new Response(this).arrayBuffer() }

This is an async method which first checks for the availability of arrayBuffer method.这是一个异步方法,它首先检查arrayBuffer方法的可用性。 This function is backward compatible and future proof.此功能向后兼容且面向未来。

async function blobToArrayBuffer(blob) {
    if ('arrayBuffer' in blob) return await blob.arrayBuffer();
    
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = () => resolve(reader.result);
        reader.onerror = () => reject;
        reader.readAsArrayBuffer(blob);
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM