Skip to content

Instantly share code, notes, and snippets.

/index.js Secret

Created Jul 31, 2017
Embed
What would you like to do?
check magic number before upload
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)
})
@jettary
Copy link

jettary commented Feb 25, 2019

You should think about JPEG RAW. According to Wiki magic number for it is ff d8 ff db

Loading

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment