Skip to content

Instantly share code, notes, and snippets.

@echessa
Last active October 1, 2018 08:54
Show Gist options
  • Save echessa/35dbc336cdb8172305ba165bbbded267 to your computer and use it in GitHub Desktop.
Save echessa/35dbc336cdb8172305ba165bbbded267 to your computer and use it in GitHub Desktop.
// Set The Storage Engine
const storage = multer.diskStorage({
destination: './public/uploads/',
filename: (req, file, cb) => {
cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
}
});
// Init Upload
const upload = multer({
storage: storage,
limits: { fileSize: 1024 * 1024 },
fileFilter: (req, file, cb) => {
checkFileType(file, cb);
}
}).single('image');
// Check File Type
const checkFileType = (file, cb) => {
// Allowed extensions
const filetypes = /jpeg|jpg|png|gif/;
// Check extension
const extname = filetypes.test(path.extname(file.originalname).toLowerCase());
// Check mime type
const mimetype = filetypes.test(file.mimetype);
if (mimetype && extname) {
return cb(null, true);
} else {
cb('Error: Images Only!');
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment