【问题标题】:Javascript File API Reading into bufferJavascript文件API读入缓冲区
【发布时间】:2021-11-30 21:58:33
【问题描述】:

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

似乎有一种实验技术ReadableStreamBYOBReader。我在 MS edge 中进行了测试,预计将支持Browser compatibility table,以及caniuse

这是我希望在支持该功能的浏览器中运行的 sn-p,您能发现错误或解释它为什么不工作吗?

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

如果它在您的浏览器中有效,请在 cmets 中告诉我。

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

【问题讨论】:

    标签: javascript cross-browser fileapi


    【解决方案1】:

    查看 MDN ReadableStream.getReader() 文档。

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

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

    【讨论】:

    • 谢谢你的回答,更进一步,现在你能告诉为什么如何从文件中构造一个字节流吗?
    猜你喜欢
    • 2018-10-02
    • 2018-07-21
    • 1970-01-01
    • 1970-01-01
    • 2013-05-20
    • 2014-01-06
    • 2019-11-26
    • 2018-08-26
    • 1970-01-01
    相关资源
    最近更新 更多