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

标签 node.js google-chrome download

我想要一个将文件发送给用户的 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/

相关文章:

javascript - NodeJs : Extract data from particular tag from body of response

node.js - 有哪些开源 Node.js CI 项目?

javascript - Node.js:使用 EventEmitter 和 Express 4.x 进行长轮询 |捕获请求关闭

javascript - 为什么 mongoose 的 deleteOne 和 findById 对已删除的 id 起作用

python - 文件的部分下载(仅更改了内容)

iOS:用于大文件下载的 NSFileHandle 与 NSOutputStream

java - servlet 下载 pdf 时,下载过程不可见

html - Div inside 按钮在 IE 中无法正常工作

javascript - 阻止 Chrome 中不包含特定模式的请求 URL

javascript - 我可以设置 TEXTAREA 元素的高度但让用户稍后调整它的大小吗?