【问题标题】:Node Express Fast CSV download to clientNode Express 快速 CSV 下载到客户端
【发布时间】:2020-11-04 19:24:47
【问题描述】:

我已经建立了一个小型节点 js BE 应用程序,在其上构建了 express 和 fastCsv 模块。期望的结果是能够将 csv 文件下载到客户端,而无需将其存储在服务器内的任何位置,因为数据是根据用户标准生成的。 到目前为止,我已经能够找到它,我使用流,因为该 csv 文件可能非常大,具体取决于用户选择。我很确定下面的代码中缺少某些东西:

const fs = require('fs');
const fastCsv = require('fast-csv');
.....
(inside api request)
.....
router.get('/', async(req, res) => {
   const gatheredData ...

   const filename = 'sometest.csv'
   
   res.writeHead(200, {
       'Content-Type': 'text/csv',
       'Content-Disposition': 'attachment; filename=' + filename
   })

   const csvDataStream = fastCsv.write(data, {headers: true}).pipe(res)

})

上面的代码以某种方式“起作用”,因为它确实返回了响应,但不是实际文件,而是 csv 文件的内容,我可以在预览选项卡中将其作为响应查看。总而言之,我试图将该数据流式传输到 csv 中并将其推送以将文件下载到客户端,而不是将其存储在服务器上。非常感谢任何提示或指示。

【问题讨论】:

  • 有什么结果吗?
  • 看起来您可能需要用双引号将filename 部分括起来,如下所示:res.header("Content-Disposition", 'attachment; filename="' + filename + '"');

标签: node.js csv express download fast-csv


【解决方案1】:

在使用 fast-csv 包在服务器上创建 CSV 文件后,这对我有用。您需要指定创建输出 CSV 文件的完整绝对目录路径:

const csv = require("fast-csv");
const csvDir = "abs/path/to/csv/dir";
const filename = "my-data.csv";
const csvOutput = `${csvDir}/${filename}`;
console.log(`csvOutput: ${csvOutput}`); // full path

/*
CREATE YOUR csvOutput FILE USING 'fast-csv' HERE
*/

res.type("text/csv");
res.header("Content-Disposition", `attachment; filename="${filename}"`);
res.header("Content-Type", "text/csv");
res.sendFile(filename, { root: csvDir });

您需要确保将响应内容类型和标头更改为"text/csv",并尝试将filename=... 部分括在双引号中,如上例所示。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-19
    • 1970-01-01
    • 1970-01-01
    • 2016-05-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多