本文介绍了在发送8个字节之前,Chrome不会显示文件已下载(Firefox会显示)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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.

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

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');
});

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

Is there a way to solve this?

具有以上代码的示例URL:

Example URLs with the code above:




  • 7 bytes are sent, download is not instant
  • 8 bytes are sent, download starts instantly

推荐答案

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

You could try prepending the file with 0-width space characters.

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');
});

这篇关于在发送8个字节之前,Chrome不会显示文件已下载(Firefox会显示)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 23:06