-
-
Save anonymous/f8d6fc6544be4e04df598f2324bfd461 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)) { | |
fs.writeFile('./uploads/' + req.file.fieldname + '-' + Date.now() + path.extname(req.file.originalname), buffer, 'binary', function (err) { | |
if (err) throw err | |
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