【问题标题】:Node+Express pipe file directly to writeStreamNode+Express管道文件直接写流
【发布时间】:2016-12-15 14:48:36
【问题描述】:

在学习方面我需要自己用fs.streams制作文件上传

router.post('/upload', (req, res, next) => {
  req.pipe(fs.createWritableStream('files/file.png'))
    .on('error', (err) => next(err))
    .on('close', () => {
      res.json({image: 'files/file.png'});
    })
})

这是行不通的。所以两个问题

  • 如何从req中获取文件名和数据?
  • 如何连接这两个流?

更新:在所有教程中描述了相反的操作 - 从 fspipe 读取文件到 res 到最终用户。

【问题讨论】:

  • 你找到解决这个问题的方法了吗?

标签: node.js express stream fs


【解决方案1】:

你可以使用multer

const multer = require('multer');
const upload = multer({
  dest: 'folderName'
});

router.post('/upload', upload.single('formField'), (req, res, next) => {
  res.json({image: req.file.path});
})

在此代码文件路径中将被发送。 如果你想发送文件本身,那么你应该写:

res.download(req.file.path);

而不是res.json({image: req.file.path})

我不知道res.download 是如何工作的。也许它会占用文件的整个缓冲区并发送它。

multer 的文档是here

【讨论】:

    猜你喜欢
    • 2017-08-25
    • 1970-01-01
    • 2022-10-13
    • 2013-12-28
    • 2022-11-21
    • 1970-01-01
    • 1970-01-01
    • 2017-11-17
    • 1970-01-01
    相关资源
    最近更新 更多