Handle callback of multer file Filter

Issue

I have write simple function to upload and write image file to server with Express + Multer
Now , i want to handle callback error to return and error message to client like

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

But , in my code , i’ve get an HTML code like that

<!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>

So , i want to ask can you help me handle the callback to return message like what i want ?

Here my code:

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 });

    });

Solution

Instead of use upload.single('file') as a middleware, you can call the function by manual, then you can control the error:

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 });
    })

  });

Answered By – hoangdv

Answer Checked By – Senaida (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.