Skip to content

Instantly share code, notes, and snippets.

@matinkaboli
Created February 11, 2018 15:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matinkaboli/415c8130b551a4c29b0a69df2700bd35 to your computer and use it in GitHub Desktop.
Save matinkaboli/415c8130b551a4c29b0a69df2700bd35 to your computer and use it in GitHub Desktop.
Check if the uploaded file is an image and then save it somewhere (with format) in nodejs
import crypto from 'crypto';
import multer from 'multer';
const storage = multer.diskStorage({
destination(req, file, cb) {
cb(null, './uploads/');
},
filename(req, file, cb) {
crypto.pseudoRandomBytes(16, (err, raw) => {
const extension = file.mimetype.split('/')[1];
if (extension === 'jpeg' || extension === 'png') {
cb(null, raw.toString('hex') +
Date.now() +
'.' +
extension);
} else {
cb(new Error('not an image'));
}
});
}
});
export default storage;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment