gpt4 book ai didi

javascript - 如何在 Deno 中将 arrayBuffer 转换为 Uint8Array?

转载 作者:行者123 更新时间:2023-12-04 00:17:34 25 4
gpt4 key购买 nike

我正在使用 fetch api 在 Deno 中下载图像。在 Response 对象上,我正在调用 arrayBuffer() 方法,以获取响应的最终数据:

const response = await fetch('https://www.example.com/someimage.jpg')
const data = await response.arrayBuffer();//This returns an arrayBuffer.
然后我想把这些数据写入一个文件,就像你在 Node 中做的那样:
await Deno.writeFile('./someimage.jpg' ,data)
图像变成空的。文档说 Deno.writeFile 需要一个 Uint8Array,但我不知道如何从从 fetch 响应中接收到的 arrayBuffer 构造它。
如何才能做到这一点?

最佳答案

您必须通过 ArrayBuffer Uint8Array构造函数

You cannot directly manipulate the contents of an ArrayBuffer;instead, you create one of the typed array objects or a DataView object which represents the buffer in a specific format, and use that to read and write the contents of the buffer.


new Uint8Array(arrayBuffer);
const response = await fetch('https://www.example.com/someimage.jpg')
const data = await response.arrayBuffer();//This returns an arrayBuffer.
await Deno.writeFile('./someimage.jpg' , new Uint8Array(data))

关于javascript - 如何在 Deno 中将 arrayBuffer 转换为 Uint8Array?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62762623/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com