javascript 如何从 Blob 到 ArrayBuffer

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15341912/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 00:27:49  来源:igfitidea点击:

How to go from Blob to ArrayBuffer

javascriptblobarraybuffer

提问by Jeanluca Scaljeri

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?

采纳答案by tripulse

The ResponseAPI consumes a (immutable) Blobfrom which the data can be retrieved in several ways. The OPonly asked for ArrayBuffer, and here's a demonstration of it.

所述ResponseAPI消耗(不可变)Blob从该数据可以以几种方式进行检索。在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 APIisn't compatible with older (ancient) browsers so take a look to the Browser Compatibility Tableto be on the safe side ;)

注意:API与较旧的(古老的)浏览器不兼容,因此请查看浏览器兼容性表以确保安全;)

回答by potatosalad

You can use FileReaderto read the Blobas an ArrayBuffer.

您可以使用FileReader将 阅读BlobArrayBuffer.

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.resultversus this.result

2018-06-23 更新:感谢 Klaus Klein 提供关于event.target.resultvs的提示this.result

Reference:

参考:

回答by Klaus Klein

Just to complement Mr @potatosalad answer.

只是为了补充@potatosalad 先生的回答。

You don't actually need to access the function scopeto get the result on the onloadcallback, you can freely do the following on the eventparameter:

您实际上并不需要访问函数作用域来获取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);

回答by Arlen Beiler

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 的网络选项卡上。

回答by Kaiido

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()将返回一个承诺与代表blob数据的ArrayBuffer解决方法。

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