Created
February 11, 2018 15:26
-
-
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
This file contains 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
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