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"); | |
}); |
Hello , why my app is hang when i hit the endpoint twice, if you try on postman, it will hang with "Sending request..." message
This is my code :
R_menu.js
const MW_MULTER = [handlerUploadImage]; router.post("/upload-image", MW_MULTER, C_menu.uploadImage);
MW_menu.js
const handlerUploadImage = (req, res) => { console.log("Handler Upload Image middleware reached"); const h = upload.single("image"); h(req, res, function (err) { if (err) { return res.status(400).send({ message: err.message }); } }); };
Every middleware should call next handler or throw error (or smth). Your handlerUploadImage takes 3 parameters: req, res and next. Call next() in your handler, and request will be transferred into C_menu.uploadImage
"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!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hello , why my app is hang when i hit the endpoint twice, if you try on postman, it will hang with "Sending request..." message
This is my code :
R_menu.js
MW_menu.js