我想要一个将文件发送给用户的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 https://repl.it/@ArturDrobinskiy/AllJumboSpellchecker?language=nodejs
有办法解决这个问题吗?
包含上述代码的示例 URL:
- 发送了 7 个字节,下载不是即时的 https://alljumbospellchecker--arturdrobinskiy.repl.co/
- 发送8个字节,立即开始下载 https://alljumbospellchecker--arturdrobinskiy.repl.co/instant
您可以尝试在文件前面添加 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');
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)