Skip to content

Instantly share code, notes, and snippets.

@matinkaboli
Created February 11, 2018 15:23
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/83840dd5f4365545898d5c750d3d942d to your computer and use it in GitHub Desktop.
Save matinkaboli/83840dd5f4365545898d5c750d3d942d to your computer and use it in GitHub Desktop.
Check if uploaded file is an image in Node.js
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