Multer将错误的文件mimetype发送给客户端

时间:2020-11-04 12:08:25

标签: node.js multer

我使用multer处理我的上传文件端点。我想接受非常特定的文件模仿类型,并且当用户尝试上传不可接受的模仿类型文件时,我要发送错误:res.status(406).send(...)。这是我尝试过的:

const express = require('express');

const multer = require('multer');

const {
    saveLogFile,
} = require('../controller/log');
const {
    bodyKeys,
} = require('../middleware/security');
const {
    getRandomInt,
} = require('../util/math');

const router = express.Router();

const storage = multer.diskStorage({
    destination(req, file, cb) {
        if (file.mimetype !== 'application/octet-stream' && file.mimetype !== 'text/plain') {
            return cb(new Error('File mimetype is invalid.'));
        }
        
        cb(null, 'data/');
    },
    filename(req, file, cb) {
        const randomPostfix = getRandomInt(1000, 9999);
        const fileName = `temp-${randomPostfix}`;

        cb(null, fileName);
    },
});
const uploader = multer({
    storage,
}).single('file');

router.post(
    '/',
    uploader,
    bodyKeys([{ key: 'type', type: 'string' }, { key: 'mode', type: 'string' }]),
    saveLogFile,
    (error, req, res) => {
        console.log(error);
        res.status(406).send(error);
    },
);

module.exports = router;

但是,当客户端在控制台(Google Chrome上的F12)中查看错误时,它将显示500错误,而不是406。我做错了什么?

关闭console.log(error)的结果:

Error: File mimetype is invalid.
    at DiskStorage.destination [as getDestination] (C:\Users\Tal\Desktop\Scanovate-Logs\backend\router\log.js:20:23)
    at DiskStorage._handleFile (C:\Users\Tal\Desktop\Scanovate-Logs\backend\node_modules\multer\storage\disk.js:31:8)
    at C:\Users\Tal\Desktop\Scanovate-Logs\backend\node_modules\multer\lib\make-middleware.js:144:17
    at allowAll (C:\Users\Tal\Desktop\Scanovate-Logs\backend\node_modules\multer\index.js:8:3)
    at wrappedFileFilter (C:\Users\Tal\Desktop\Scanovate-Logs\backend\node_modules\multer\index.js:44:7)
    at Busboy.<anonymous> (C:\Users\Tal\Desktop\Scanovate-Logs\backend\node_modules\multer\lib\make-middleware.js:114:7)
    at Busboy.emit (events.js:315:20)
    at Busboy.emit (C:\Users\Tal\Desktop\Scanovate-Logs\backend\node_modules\busboy\lib\main.js:38:33)
    at PartStream.<anonymous> (C:\Users\Tal\Desktop\Scanovate-Logs\backend\node_modules\busboy\lib\types\multipart.js:213:13)     
    at PartStream.emit (events.js:315:20)
    at HeaderParser.<anonymous> (C:\Users\Tal\Desktop\Scanovate-Logs\backend\node_modules\dicer\lib\Dicer.js:51:16)
    at HeaderParser.emit (events.js:315:20)
    at HeaderParser._finish (C:\Users\Tal\Desktop\Scanovate-Logs\backend\node_modules\dicer\lib\HeaderParser.js:68:8)
    at SBMH.<anonymous> (C:\Users\Tal\Desktop\Scanovate-Logs\backend\node_modules\dicer\lib\HeaderParser.js:40:12)
    at SBMH.emit (events.js:315:20)
    at SBMH._sbmh_feed (C:\Users\Tal\Desktop\Scanovate-Logs\backend\node_modules\streamsearch\lib\sbmh.js:159:14)

0 个答案:

没有答案