Skip to content

Instantly share code, notes, and snippets.

@whisher
Created August 11, 2018 15:07
Show Gist options
  • Save whisher/bd8aa11f35ef493f237fa5f7bcb72e59 to your computer and use it in GitHub Desktop.
Save whisher/bd8aa11f35ef493f237fa5f7bcb72e59 to your computer and use it in GitHub Desktop.
'use strict';
const multer = require('multer');
const MIME_TYPE_MAP = {
'image/png': 'png',
'image/jpeg': 'jpg',
'image/jpg': 'jpg'
};
const storage = multer.diskStorage({
destination: (req, file, cb) => {
let error = null;
const isValid = MIME_TYPE_MAP[file.mimetype];
if (!isValid) {
error = new Error('Invalid mime type');
}
cb(error, 'images');
},
filename: (req, file, cb) => {
const name = file.originalname
.toLowerCase()
.split(' ')
.join('-');
const ext = MIME_TYPE_MAP[file.mimetype];
cb(null, name + '-' + Date.now() + '.' + ext);
}
});
module.exports = multer({ storage: storage }).single('image');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment