node.js - 如何以express方式发送缓冲区数据?

标签 node.js express buffer

我正在尝试创建一个 Excel 文件并将其发送给客户。客户端应该通过ajax请求下载文件,因为我需要过滤器参数。

我正在使用 excel4node 包来创建 Excel 文件。

我编写了下面的代码,它现在可以工作,但我怀疑如果我的数据大于缓冲区会怎样。这是使用缓冲区的正确方法吗? (请使用 writeToBuffer 方法检查该行)

    const xl = require('excel4node');

    const excelCreator = function (data) {...}

    app.post('/api/excel', jsonParser, (req, res) => {

      let reqObj = {
        method: 'post',
        url: apiUrl + '/MemberService';,
        headers: {
          'Content-Type': 'application/json'
        },
        data: req.body
      };

      axios(reqObj)
        .then(response => {
          res.body = responseHandler(response); // a helper function to set res object

          let data = res.body.Data;

          res.setHeader('Content-Disposition', 'attachment; filename=' + 'excel.xlsx');
          res.type('application/octet-stream');
          res.body.Data = null;

          excelCreator(data).writeToBuffer().then(function (buffer) {
            res.body.Data = buffer;
            res.send(res.body);
          });

        })
        .catch(...);
    });

最佳答案

首先安装SheetJS js-xlsx

npm --save install xlsx

然后您可以通过 Express 发送此回复:

const xlsx = require('xlsx')

var wb = xlsx.utils.book_new();

var table = [['a', 'b', 'c'], ['1', '2', '3']]
var ws = xlsx.utils.aoa_to_sheet(table);
xlsx.utils.book_append_sheet(wb, ws, 'test');

// write options
const wopts = { bookType: 'xlsx', bookSST: false, type: 'base64' };
const buffer = xlsx.write(wb, wopts);

res.writeHead(200, [['Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet']]);
res.end(new Buffer(buffer, 'base64'));

请随时查看文档 https://www.npmjs.com/package/xlsx

关于node.js - 如何以express方式发送缓冲区数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51063253/

相关文章:

java - Java中的 jitter buffer 实现

mysql - 在 Node js 应用程序中将 <用户名>@<计算机名> 更改为 <用户名>@localhost

node.js - app.all ('*' ) 和 app.use ('/' ) 之间的区别

vim - 在 vim : "((1) of 3)" in status line 中编辑多个缓冲区

c# - C#中读取套接字时算术运算溢出

javascript - 如何修复这个错误? (http ://localhost:3000/favicon. ico 404(未找到))

javascript - 使 Alexa Skill Loop 成为语音功能

node.js - CORS 预检请求后 302 重定向到 nodejs 服务器

mysql - NodeJS 和 MySQL : getting array data inside query callback

node.js - 使用 OAuth2 处理重定向代码