How to catch the MulterError: Unexpected field when the number of the files exceeds the limit?

How to catch the MulterError: Unexpected field when the number of the files exceeds the limit?

我希望能够在上传的文件超过设置限制时检测到 MulterError: Unexpected field

目前我的 app.js Node.js 应用程序中有以下代码,但它没有捕获到此错误。有什么问题吗?

var multer = require('multer')
var storage = multer.diskStorage({
    destination: function(req, file, cb) {
        cb(null, './tmsap')
    },
    filename: function(req, file, cb) {
        cb(null, file.originalname)
    },
})
var upload = multer({ 
    storage: storage,
    onError:  function(err, next) {
       console.log('Upload Error')
       res.error('There was an error when uploading your files. Perhaps, you attached too many? Please, try again.')
       res.redirect('back')
    }
})


app.post(
    '/import/files',
    upload.array('uploadedFiles', 50),
    imports.submit
)

您可以向 multer 中间件添加回调以检查错误:

app.post('/import/files', (req, res, next) => {
    upload(req, res, (err) => {
        if (err instanceof multer.MulterError && err.code === "LIMIT_UNEXPECTED_FILE") {
            // handle multer file limit error here
        } else if (err) {}
        // handle other errors... }
        else {
            // make sure to call next() if all was well
            next();
        }
    })
}, imports.submit);