gpt4 book ai didi

node.js - 在发送 8 个字节之前,Chrome 不会将文件显示为正在下载(Firefox 会)

转载 作者:IT老高 更新时间:2023-10-28 23:08:50 24 4
gpt4 key购买 nike

我想要一个将文件发送给用户的 http 方法,但它需要一些时间(例如 4 秒)来生成文件内容。

我想要的是浏览器立即显示正在下载的文件。但 Chrome 仅在发送 8 个字节后显示文件正在下载。我不知道我文件的前 8 个字节。但是,Firefox 会立即显示下载。

这是示例(在 Express 中,但后端技术无关紧要,我在 ASP.Net 中有相同的示例):

const express = require('express');

const app = express();
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms))

app.get('/:type?', async (req, res) => {
res.set("Content-type", "application/octet-stream");
res.set("Content-Disposition", "attachment;filename=\"Report.txt\"");

res.write('1234567');
if (req.params.type == "instant")
res.write('8'); //if I send 8 bytes before sleep, file downloading appears instantly
await sleep(4*1000);

res.write('9');
res.end();
});

app.listen(3000, () => {
console.log('server started');
});

https://repl.it/@ArturDrobinskiy/AllJumboSpellchecker?language=nodejs

有没有办法解决这个问题?

上面代码的示例 URL:

最佳答案

您可以尝试在文件前添加 0 宽度的空格字符。

const express = require('express');

const app = express();
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms))

app.get('/:type?', async (req, res) => {
res.set("Content-type", "application/octet-stream");
res.set("Content-Disposition", "attachment; filename=\"Report.txt\"");
res.write('\u200B\u200B\u200B\u200B\u200B\u200B\u200B\u200B');
//res.write('1234567');
if (req.params.type == "instant")
res.write('8'); //if I send 8 bytes before sleep, file downloading appears instantly
await sleep(4*1000);

res.write('9');
res.end();
});

app.listen(3000, () => {
console.log('server started');
});

关于node.js - 在发送 8 个字节之前,Chrome 不会将文件显示为正在下载(Firefox 会),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52913925/

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