gpt4 book ai didi

javascript - 如何在浏览器上下载从 fetch 返回的 ReadableStream

转载 作者:行者123 更新时间:2023-12-04 11:47:14 27 4
gpt4 key购买 nike

我从服务器接收到一个 ReadableStream,它是从我的 fetch 调用返回的。
返回一个 ReadableStream 但我不知道如何从这个阶段触发下载。我不能在 href 中使用 url,因为它需要授权 token 。
我不想安装 fs在客户端上,我有什么选择?

  try {
const res = await fetch(url, {
method: 'GET',
headers: {
Authorization: `Bearer ${token}`,
'Content-Type': 'application/octet-stream'
}
});

const blob = await res.blob();

const newBlob = new Blob([blob]);
const newUrl = window.URL.createObjectURL(newBlob);

const link = document.createElement('a');
link.href = newUrl;
link.setAttribute('download', 'filename');
document.body.appendChild(link);
link.click();
link.parentNode.removeChild(link);

window.URL.revokeObjectURL(newBlob);
} catch (error) {
console.log(error);
}
更新 1
我将文件转换为 Blob,然后将其传递给新生成的 href。成功下载了一个文件。最终结果是 ReadStream 内容为 .txt 文件。
像这样的意思
x:ÚêÒÓ%¶âÜTb∞\܃

最佳答案

我找到了 2 个解决方案,两者都有效,但我缺少一个简单的补充来使它们工作。
native 解决方案是

  try {
const res = await fetch(url, {
method: 'GET',
headers: {
Authorization: `Bearer ${token}`
}
});

const blob = await res.blob();
const newBlob = new Blob([blob]);

const blobUrl = window.URL.createObjectURL(newBlob);

const link = document.createElement('a');
link.href = blobUrl;
link.setAttribute('download', `${filename}.${extension}`);
document.body.appendChild(link);
link.click();
link.parentNode.removeChild(link);

// clean up Url
window.URL.revokeObjectURL(blobUrl);

这个版本使用 npm 包 steamSaver 供任何喜欢它的人使用。
  try {
const res = await fetch(url, {
method: 'GET',
headers: {
Authorization: `Bearer ${token}`
}
});

const fileStream = streamSaver.createWriteStream(`${filename}.${extension}`);
const writer = fileStream.getWriter();

const reader = res.body.getReader();

const pump = () => reader.read()
.then(({ value, done }) => {
if (done) writer.close();
else {
writer.write(value);
return writer.ready.then(pump);
}
});

await pump()
.then(() => console.log('Closed the stream, Done writing'))
.catch(err => console.log(err));
它为什么不起作用的关键是因为我没有包含扩展名,所以它要么因为 mimetype 错误而出错,要么它打开一个带有正文字符串而不是图像的 .txt 文件。

关于javascript - 如何在浏览器上下载从 fetch 返回的 ReadableStream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63942715/

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