Created
March 17, 2020 15:36
-
-
Save huynhsamha/348722d47ee457454688698ff77fee1a to your computer and use it in GitHub Desktop.
Example for multer upload custom error handling
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const express = require('express') | |
const multer = require('multer'); | |
const app = express(); | |
const storage = multer.diskStorage({ | |
destination: function (req, file, cb) { | |
cb(null, 'tmp') | |
}, | |
filename: function (req, file, cb) { | |
cb(null, file.fieldname + '-' + Date.now()) | |
} | |
}) | |
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 | |
}) | |
}) | |
}) | |
app.listen(3000, () => { | |
console.log("Server is listening on port: 3000"); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
"Hello @nacza,
I've encountered an issue while uploading '.png' files and it seems you're facing the same problem. Could you please review my code on GitHub (https://github.com/codal-umistri/Multer).
It will help You!