I want to have an http method that sends the file to the user, but it needs some time (e.g. 4 seconds) to generate file content.
What I want, is the browser to instantly show the file as being downloaded. But Chrome only shows the file as being downloaded after 8 bytes are send. I don't know the first 8 bytes of my file upfront. Firefox, however, shows the download instantly.
Here's the example (in Express, but backend technology doesn't matter, I had the same example in 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
Is there a way to solve this?
Example URLs with the code above: