【问题标题】:How to implement a file download with Node.js's fs module and express如何使用 Node.js 的 fs 模块实现文件下载和 express
【发布时间】:2011-09-30 09:09:26
【问题描述】:

因为文件应该是动态生成的,也许我应该使用 fs 模块的 writeStream。但是我无法通过谷歌搜索找到任何示例代码。对不起。

更具体地说,当有人请求时,我想在 MongoDB 中提供包含我的数据的 CSV 文件或 PDF 文件。

任何人,请给我一些提示。

谢谢。

【问题讨论】:

    标签: node.js download express


    【解决方案1】:

    您不需要 fs,只需在请求处理程序中从 db 流式传输您的数据

    您可以使用Content-Disposition header 设置文件元数据

    Content-Type: image/jpeg
    Content-Disposition: attachment; filename=genome.jpeg; 
      modification-date="Wed, 12 Feb 1997 16:29:51 -0500";
    Content-Description: a complete map of the human genome
    

    【讨论】:

    • 非常感谢。我会试试这个方法。
    【解决方案2】:

    有了express,我可以这样实现。

    app.get('/down2', function(req, res){
      var filename = 'data.csv';
      res.attachment(filename);
      res.end('hello,world\nkeesun,hi', 'UTF-8'); //Actually, the data will be loaded form db.
    });
    

    它是多么简单。谢谢。

    【讨论】:

    • 如果您从 db 链接接收到 csv 数据并且它在第一名。你已经有了数据,为什么不设置标题然后res.send(generatedCSVcontent)
    • 我没有将数据保存到某个文件中。我只是按照你说的发送数据。上面的文件名只是用于请求标头的文件名。实际上, res.attachment() 与第一个答案非常相似。它只是用文件名和内容类型设置标题。
    • @Whiteship res.end 不应该用于较大的文件,否则它将始终下载 0 字节的文件
    猜你喜欢
    • 2017-02-20
    • 2015-07-09
    • 1970-01-01
    • 2011-04-29
    • 2020-07-08
    • 2015-10-29
    • 2020-10-22
    • 2012-12-09
    • 2015-02-10
    相关资源
    最近更新 更多