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> at fileFilter (C:\Users\reale\source\repos\ChamCongAPI\routes\index.js:35:29)<br> at wrappedFileFilter (C:\Users\reale\source\repos\ChamCongAPI\node_modules\multer\index.js:44:7)<br> at Busboy.<anonymous> (C:\Users\reale\source\repos\ChamCongAPI\node_modules\multer\lib\make-middleware.js:114:7)<br> at Busboy.emit (events.js:182:13)<br> at Busboy.emit (C:\Users\reale\source\repos\ChamCongAPI\node_modules\busboy\lib\main.js:38:33)<br> at PartStream.<anonymous> (C:\Users\reale\source\repos\ChamCongAPI\node_modules\busboy\lib\types\multipart.js:213:13)<br> at PartStream.emit (events.js:182:13)<br> at HeaderParser.<anonymous> (C:\Users\reale\source\repos\ChamCongAPI\node_modules\dicer\lib\Dicer.js:51:16)<br> at HeaderParser.emit (events.js:182:13)<br> 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 });
});
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 });
})
});