-
-
Save anonymous/3eb41bad8e9bc7ef55714606cc31b2b9 to your computer and use it in GitHub Desktop.
check magic number before upload
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
var express = require("express") | |
var multer = require('multer') | |
var app = express() | |
var path = require('path') | |
var fs = require('fs') | |
var ejs = require('ejs') | |
app.set('view engine', 'ejs') | |
var MAGIC_NUMBERS = { | |
jpg: 'ffd8ffe0', | |
jpg1: 'ffd8ffe1', | |
png: '89504e47', | |
gif: '47494638' | |
} | |
function checkMagicNumbers(magic) { | |
if (magic == MAGIC_NUMBERS.jpg || magic == MAGIC_NUMBERS.jpg1 || magic == MAGIC_NUMBERS.png || magic == MAGIC_NUMBERS.gif) return true | |
} | |
app.get('/api/file', function(req, res) { | |
res.render('index') | |
}) | |
var upload = multer({ | |
storage: multer.memoryStorage() | |
}).single('userFile') | |
app.post('/api/file', function(req, res) { | |
upload(req, res, function(err) { | |
var buffer = req.file.buffer | |
var magic = buffer.toString('hex', 0, 4) | |
if (checkMagicNumbers(magic)) { | |
var wstream = fs.createWriteStream('./uploads/' + req.file.fieldname + '-' + Date.now() + path.extname(req.file.originalname)) | |
wstream.write(buffer) | |
res.end('File is uploaded') | |
} else { | |
res.end('File is no valid') | |
} | |
}) | |
}) | |
var port = process.env.PORT || 8080 | |
app.listen(port, function() { | |
console.log('Node.js listening on port ' + port) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You should think about JPEG RAW. According to Wiki magic number for it is
ff d8 ff db