我就是这样用穆特的,

const specialExample = multer({ .. blah blah })
app.post(
    '/specialPath',
    specialExample.single('handled_by_multer'),
    await function (req, res) {
        fs.renameSync(.. move the file, etc
        // send a reply
        res.set('Content-Type', 'text/plain')
        res.status(200).send(`ok`)
    })

所以请注意,事情按如下顺序发生:

app.post(
    '/specialPath',
// EXPRESS KNOWS TO GO THIS WAY
    specialExample.single('handled_by_multer'),
// MULTER LITERALLY IS GETTING THE FILE
// MULTER HAS COMPLETELY GOT AND SAVED THE FILE
    await function (req, res) {
// THIS FUNCTION NOW BEGINS RUNNING
        ... etc

这一切都很好.

现在,想象一下,我想看看一些参数.

在某些情况下,我DO NOT想要得到文件.

const specialExample = multer({ .. blah blah })
app.post(
    '/specialPath',
    specialExample.single('handled_by_multer'),
    await function (req, res) {
        const meta = req.body.meta
        if (meta !== "wth") {
           .. we actually DON'T want the  file
           .. delete the file
           .. send a 401 and return
        }
        fs.renameSync(.. move the file, etc
        // send a reply
        res.set('Content-Type', 'text/plain')
        res.status(200).send(`ok`)
    })

请注意,这可以很好地工作,但是,我们正在浪费地获取/保存文件(然后才删除它).

有没有办法做更多这样的事情......

app.post(
    '/specialPath',

    await function (req, res) {
        .. if I happen to want to, only then: {
            specialExample.single('handled_by_multer'),
        }
    })

怎么做?

推荐答案

因为multer是解析存储在req.body中的字段数据的中间件,所以您不能有条件地调用它.

相反,如果满足您的条件,则可以使用Multer的fileFilter忽略文件数据:

const specialExample = multer({
  fileFilter(req, file, cb) {
    const meta = req.body.meta;
    if (meta !== "wth") {
      // reject this file
      return cb(null, false);
    }
    return cb(null, true);
  },
  .. blah blah
});
...
app.post(
    '/specialPath',
    specialExample.single('handled_by_multer'),
    await function (req, res) {
      // also have to check here to make sure the correct response is sent
      const meta = req.body.meta
      if (meta !== "wth") {
        return res.sendStatus(401);
      }
      ...
    }
);    

一个可能的问题是:您用来判断文件是否应该被拒绝的字段(本例中为meta)需要放入文件数据的多部分数据before中,否则在调用fileFilter()时它将不会被填充.

Node.js相关问答推荐

在child_Process中持久运行SSH命令

如何解决TypeError:requ.isAuthenticated不是函数错误?

如何将信号从终端窗口发送到运行在Raspberry Pi上的Puppeteer/Node.js上的webscraper

使用 axios 和 Cheerio (Node js) 抓取 google 搜索

在 azure blob 容器之间复制文件

将图像添加到多个产品的条带 checkout 会话中

几个 lambda 共有的函数

与诗乃一起嘲笑奈克斯

为什么 client.on("messageCreate") 的 TextChannel 中缺少 nsfw 属性?

处理 UTC 日期和future

如何删除mongodb中嵌套数组中所有出现的数组元素

NodeJS 中的流 API 数据如何流动?

Express.js cookie setter 的 Domain 属性:如何与 *多个 * 域共享 cookie?

JAVASCRIPT:foreach 循环后的空数组

是Electron 的密码和登录凭据的安全存储吗?

使用 firebase 函数 api 运行套接字(相同的端口创建问题)

Mongodb v4.0 Transaction, MongoError: Transaction numbers are allowed on a replica set member or mongos

如何在 Node.js 中等待子进程完成

代理(如提琴手)可以与 Node.js 的 ClientRequest 一起使用吗

如何阻止 babel 将this转换为undefined(并插入use strict)