I'm writing code for image upload in NodeJS using multer
My code is
var upload = multer({
storage: storage,
limits: {
fileSize: 1024 * 1024 * 5
},
fileFilter: (req, file, cb) => {
if (file.mimetype == "image/png" || file.mimetype == "image/jpg" || file.mimetype == "image/jpeg") {
cb(null, true);
} else {
return cb(JSON.stringify({ "success": false, "message": "invalid mime type" }), false);
}
}
});
router.post('/upload', upload.single('image'), (req, res, next) => {
const io = req.app.get('io');
const product = new db.product({
name: req.body.name,
category: req.body.category,
image: req.protocol + "://" + req.hostname + ":" + req.socket.localPort + "/img/roundtshirt/" + req.file.filename
});
});
When I upload an invalid file from Postman, I got the following error such as my callback
<pre>{"success":false,"message":"invalid mime type"}</pre>
However, I want to convert that error to proper json format.
I've tried returning json but got an error.
You can use custom error handling from Multer here
This is my example:
const upload = multer({
storage: storage,
limits: {
fileSize: 1024 * 1024 * 5
},
fileFilter: (req, file, cb) => {
if (file.mimetype == "image/png" || file.mimetype == "image/jpg" || file.mimetype == "image/jpeg") {
cb(null, true);
} else {
return cb(new Error('Invalid mime type'));
}
}
});
const uploadSingleImage = upload.single('image');
app.post('/upload', function (req, res) {
uploadSingleImage(req, res, function (err) {
if (err) {
return res.status(400).send({ message: err.message })
}
// Everything went fine.
const file = req.file;
res.status(200).send({
filename: file.filename,
mimetype: file.mimetype,
originalname: file.originalname,
size: file.size,
fieldname: file.fieldname
})
})
})
For the full example code, please visit https://gist.github.com/huynhsamha/348722d47ee457454688698ff77fee1a
Thank for reading :D
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With