node.js - 在 Express 中使用 Multer 设置响应状态?

标签 node.js http express multer

我正在使用 Multer 作为 Express 中间件。在我的示例中,我正在检查文件扩展名和 mimetype 是否正确(对于 wave 文件),如果不正确,我想用 415 进行响应。但是我不知道如何使用 Multer 的 fileFilter 执行此操作,所以我正在检查该文件是否存在于路由器处理程序的请求对象中,这感觉有点尴尬。也可能我想在未来实现不同的 fileFilter 和错误代码。在 Express 中使用 Multer 设置响应状态是否有推荐的模式?

const upload = multer(
{
  dest: UPLOAD_PATH,
  fileFilter: function(req, file, cb) {
    const filetypes = /wave|wav/;
    const mimetype = filetypes.test(file.mimetype);
    const extname = filetypes.test(
        path.extname(file.originalname).toLowerCase());
    cb(null, (mimetype && extname));
  },
}
);

router.post('/', upload.single('wave'), (req, res) => {
  const file = req.file;
  if (!file) {
    return res.status(415).send('Only audio/wav files are supported.');
  }
  // Do some async task with file
  return res.sendStatus(200);
});

最佳答案

你可以这样做:

const upload = multer({
    dest: 'uploads/',
    fileFilter: function (req, file, cb) {
        const filetypes = /wave|wav/;
        const mimetype = filetypes.test(file.mimetype);
        const extname = filetypes.test(
            path.extname(file.originalname).toLowerCase());

        if (mimetype && extname) {
            cb(undefined, true);
        } else {
            req.notWAVEMimeType = 'Only audio/wav files are supported.';
            return cb(undefined, false);
        }
    }
});

router.post('/', upload.single('wave'), (req, res) => {
    if (req.notWAVEMimeType) {
        return res.status(415).end(req.notWAVEMimeType);
    }

    // Do some async task with file
    return res.sendStatus(200);
});

请求对象上的 notWAVEMimeType 属性允许您将错误消息返回到 POST 方法。根据这个你可以添加其他mime类型,然后检查req的相关属性是否存在。

关于node.js - 在 Express 中使用 Multer 设置响应状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52833003/

相关文章:

node.js heroku Ghost 由于缺少依赖项而无法启动 : Cannot find module

python - 如何在 Scrapy 中创建带方括号的 url 请求?

http - IIS 文件下载挂起/超时 - sc-win32-status = 64

javascript - node.js 多人 html5 游戏中的延迟越来越高

node.js - 在子文件夹中运行 mocha 测试

javascript - 如果该值存在于所有数组中则返回 true

node.js - 按关联模型排序时,Sequelize 抛出错误 "Unable to find a valid association for model x"

使用 connect-redis 和 Unix 域套接字的 Node.js Express session

node.js - 即使在设置代理后,npm install express --save 命令也会给出 403 禁止错误

php - 有两个同名 HTTP GET 参数时的行为