处理多文件过滤器的回调

Handle callback of multer file Filter

我已经编写了简单的函数来使用 Express + Multer 将图像文件上传和写入服务器 现在,我想处理 return 的回调错误和给客户端的错误消息,比如

{success:false,message:'Only image are allowed'}

但是,在我的代码中,我得到了这样的 HTML 代码

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Error: Only images are allowed<br> &nbsp; &nbsp;at fileFilter (C:\Users\reale\source\repos\ChamCongAPI\routes\index.js:35:29)<br> &nbsp; &nbsp;at wrappedFileFilter (C:\Users\reale\source\repos\ChamCongAPI\node_modules\multer\index.js:44:7)<br> &nbsp; &nbsp;at Busboy.&lt;anonymous&gt; (C:\Users\reale\source\repos\ChamCongAPI\node_modules\multer\lib\make-middleware.js:114:7)<br> &nbsp; &nbsp;at Busboy.emit (events.js:182:13)<br> &nbsp; &nbsp;at Busboy.emit (C:\Users\reale\source\repos\ChamCongAPI\node_modules\busboy\lib\main.js:38:33)<br> &nbsp; &nbsp;at PartStream.&lt;anonymous&gt; (C:\Users\reale\source\repos\ChamCongAPI\node_modules\busboy\lib\types\multipart.js:213:13)<br> &nbsp; &nbsp;at PartStream.emit (events.js:182:13)<br> &nbsp; &nbsp;at HeaderParser.&lt;anonymous&gt; (C:\Users\reale\source\repos\ChamCongAPI\node_modules\dicer\lib\Dicer.js:51:16)<br> &nbsp; &nbsp;at HeaderParser.emit (events.js:182:13)<br> &nbsp; &nbsp;at HeaderParser._finish (C:\Users\reale\source\repos\ChamCongAPI\node_modules\dicer\lib\HeaderParser.js:68:8)</pre>
</body>
</html>

所以,我想问一下你能帮我处理对 return 消息的回调吗?

这是我的代码:

var upload = multer({
    storage: storage,
    fileFilter: function (req, file, callback) {
        var ext = path.extname(file.originalname);
        if (ext !== '.png' && ext !== '.jpg' && ext !== '.gif' && ext !== '.jpeg') {
            return callback(new Error('Only images are allowed'));
        }
        callback(null, isValid(req));
    },


});
router.post('/upload',
    upload.single('file'),
    (req, res, error) => {
        if (error)
            console.log(error);
        const file = req.file;
        console.log(req);
        if (!file) {
            return res.status(500)send({ success: false, message: "Please upload a file" });
        } 
        res.send({ success: true, fileInfo: file.path });

    });

不用upload.single('file')做中间件,可以手动调用函数,这样就可以控制错误了:

var upload = multer({
  storage: storage,
  fileFilter: function (req, file, callback) {
    var ext = path.extname(file.originalname);
    if (ext !== '.png' && ext !== '.jpg' && ext !== '.gif' && ext !== '.jpeg') {
      return callback(new Error('Only images are allowed'));
    }
    callback(null, isValid(req));
  },


});

var uploadSingle = upload.single('file');

router.post('/upload',
  (req, res) => { // 3rd param of Request handler is next function, not error object
    uploadSingle(req, res, (err) => { // call as a normal function
      if (err) return res.status(500).send({ success: false, message: 'Only image are allowed' })

      console.log('save the file', req.file)

      const file = req.file;
      console.log(req);
      if (!file) {
        return res.status(500).send({ success: false, message: "Please upload a file" });
      }

      res.send({ success: true, fileInfo: file.path });
    })

  });

对于仍在使用 multer 作为中间件寻找答案的更多人,您可以在 req 中将布尔值设置为 属性,然后将其传递给您的控制器:

路由器

const upload = multer({
    fileFilter: (req, file, cb) => {
        // Allowed extensions
        const allowedExt = /jpg|png/
        let checkExt = allowedExt.test(path.extname(file.originalname).toLowerCase())
        let checkMimeType = allowedExt.test(file.mimetype)

        // You can set a property in req
        req.isFileValid = checkExt && checkMimeType

        cb(null, checkExt && checkMimeType)
    }
})

router.post('/', upload.single('image'), MyController.upload)

控制器

exports.upload = (req, res) => {
    if(req.isFileValid === false) {
        return res.status(500).send({
            success: false,
            message: `Only image are allowed`
        })
    }
}