繁体   English   中英

Javascript File API 读入缓冲区

[英]Javascript File API Reading into buffer

我有兴趣从文件读取到我自己的缓冲区,以避免额外的副本。

似乎有一种实验技术ReadableStreamBYOBReader 我在 MS edge 中进行了测试,预计将相应地支持浏览器兼容性表以及caniuse

这是我希望在支持该功能的浏览器中运行的代码段,您能发现错误或解释为什么它不起作用吗?

 console.log(navigator.userAgent) document.querySelector('#input-file').addEventListener('change', async (e) => { if(e.target.files[0]){ try{ // Compare two methods of reading a file const file = e.target.files[0]; const stream = file.stream(); const slice = await file.slice(0, Math.min(file.size, 16)).arrayBuffer() const my_own_array = new Uint8Array(Math.min(file.size, 16)); // Here is where it fails in my browser const reader = stream.getReader({mode:'byob'}) console.log(await reader.read(my_own_array)); slice_array = new Int8Array(slice); // I expect both arrays to have the same data since I read the same file console.log({allEqual: slice_array.every((v, i) => v === my_wn_array[i])}) console.log(my_own_buffer); }catch(e){ console.log(e.toString()) } } })
 Select a file and the script will attempt to load it <input type=file id=input-file>

我在这里看到的是

Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.71 Safari/537.36 Edg/94.0.992.38`
TypeError: Failed to execute 'getReader' on 'ReadableStream': Cannot use a BYOB reader with a non-byte stream

如果它适用于您的浏览器,请在评论中告诉我。

编辑:正如Xeelley所指出的,我应该通过{mode:'byob'}而不是'byob'

检查 MDN ReadableStream.getReader()文档。

getReader接受类型为object 1 个可选参数。 所以如果你需要 BYOB 阅读器,你应该像这样传递阅读器配置:

file.stream().getReader({ mode: 'byob' })

暂无
暂无

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

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