NodeJS Multer fileFilter不工作(它不返回404错误状态)

nuypyhwy  于 2023-06-22  发布在  Node.js
关注(0)|答案(1)|浏览(137)

这是我的Multer配置文件

module.exports = (multer({
    storage: multer.diskStorage({
        destination: (req, file, cb) => {
            cb(null, './public/upload/especies')
        },
        filename: (req, file, cb) => {
            cb(null, Date.now().toString() + "_" + file.originalname)
        }
    }),
    fileFilter: function (req, file, cb) {
        if (!file.originalname.match(/\.(jpg|jpeg|png)$/)) {
            console.log('false')
            return cb(null, false);
        }
        console.log('true')
        return cb(null, true);
    }
}))

然后我调用这个文件config作为上传图像路由器内部的中间件

const router = express.Router();

const uploadImg = require("../middlewares/UploadImageEspecie");

router.post("/uploadImg", uploadImg.array('images', 12), async (req, res) => {
    if (req.files) {
        console.log(req.files)
        return res.json({
            error: false,
            message: "Upload realizado com sucesso!"
        })
    }
    else {
        return res.status(400).json({
            error: true,
            message: 'Erro: Upload não realizado com sucesso, necessário enviar imagens no formato PNG, JPG ou JPEG.'
        })
    }
});

module.exports = router;

但是,由于某种原因,当我尝试上传一些.mp4或.psd扩展名的文件时,它不会返回错误404状态,并且还会打印console.log false。为什么会这样?

0sgqnhkj

0sgqnhkj1#

在multer的filter的回调函数中,第一个参数应该是一个Error的示例,如new Error('Invalid file format')

module.exports = (multer({
    storage: multer.diskStorage({
        destination: (req, file, cb) => {
            cb(null, './public/upload/especies')
        },
        filename: (req, file, cb) => {
            cb(null, Date.now().toString() + "_" + file.originalname)
        }
    }),
    fileFilter: function (req, file, cb) {
        if (!file.originalname.match(/\.(jpg|jpeg|png)$/)) {
            console.log('false')
            return cb(new Error('Invalid file format'), false);
        }
        console.log('true')
        return cb(null, true);
    }
}))

相关问题