【问题标题】:nodejs input stream using express使用express的nodejs输入流
【发布时间】:2017-10-18 12:52:02
【问题描述】:

有没有办法使用 express 路由消费者可以将输入流发送到端点并读取它?

简而言之,我希望端点用户通过流式传输文件而不是 multipart/form 方式上传文件。比如:

app.post('/videos/upload', (request, response) => {
    const stream = request.getInputStream();
    const file = stream.read();
    stream.on('done', (file) => {
        //do something with the file
    });
});

有可能吗?

【问题讨论】:

标签: node.js express inputstream


【解决方案1】:

在 Express 中,request 对象是 http.IncomingMessage 的增强版本,“...实现了 Readable Stream 接口”

换句话说,request 已经是一个流:

app.post('/videos/upload', (request, response) => {
  request.on('data', data => {
    ...do something...
  }).on('close', () => {
    ...do something else...
  });
});

如果您的意图是先将整个文件读入内存(可能不是),您也可以使用bodyParser.raw()

const bodyParser = require('body-parser');
...
app.post('/videos/upload', bodyParser.raw({ type : '*/*' }), (request, response) => {
  let data = req.body; // a `Buffer` containing the entire uploaded data
  ...do something...
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-25
    • 2020-12-31
    • 1970-01-01
    • 1970-01-01
    • 2020-08-31
    • 2012-06-13
    • 2013-11-14
    • 1970-01-01
    相关资源
    最近更新 更多