使用Node / Express将文件流式传输给用户进行下载

时间:2016-11-18 23:23:04

标签: node.js express

我想使用Node / Express服务器将文件作为附件流式传输到客户端。我想从客户端向/download端点发出异步请求,然后将通过API代理接收的对象作为可下载文件提供给客户端(类似于res.attachment(filename); res.send(body);的行为方式)。

例如:

fetch(new Request('/download'))
    .then(() => console.log('download complete'))

app.get('/download', (req, res, next) => {
    // Request to external API
    request(config, (error, response, body) => {
        const jsonToSend = JSON.parse(body);
        res.download(jsonToSend, 'filename.json');
    })
});

这不起作用,因为res.download()只接受文件的路径。我想从内存中的对象发送响应。现有的Node / Express API如何实现这一目标?

设置适当的标题不会触发下载:

    res.setHeader('Content-disposition', 'attachment; filename=filename.json');
    res.setHeader('Content-type', 'application/json');
    res.send({some: 'json'});

2 个答案:

答案 0 :(得分:2)

这对我有用。 我使用内容类型octet-stream强制下载。 在chrome上测试,json被下载为' data.json'
您无法根据以下内容使用ajax进行下载:Handle file download from ajax post

您可以使用href / window.location / location.assign。此浏览器将检测mime类型application/octet-stream并且不会更改实际页面仅触发下载,因此您可以将其包装成ajax成功调用。

//client
const endpoint = '/download';

fetch(endpoint, {
  method: 'POST',
  credentials: 'include',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
  }
  })
  .then(res => res.json())
  .then(res => {
     //look like the json is good to download
     location.assign(endpoint);
   })
   .catch(e => {
     //json is invalid and other e
   });

//server
const http = require('http');

http.createServer(function (req, res) {
    const json = JSON.stringify({
      test: 'test'
    });
    const buf = Buffer.from(json);
    res.writeHead(200, {
      'Content-Type': 'application/octet-stream',
      'Content-disposition': 'attachment; filename=data.json'
    });
    res.write(buf);
    res.end();
}).listen(8888);

答案 1 :(得分:0)

您可以设置标题以强制下载,然后使用res.send

查看这些链接