我希望有一个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
有没有办法解决这个问题?
具有上述代码的示例网址:
答案 0 :(得分:1)
您可以尝试在文件前添加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');
});