Skip to content

Instantly share code, notes, and snippets.

/index.js Secret

Created July 31, 2017 02:20
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 anonymous/f8d6fc6544be4e04df598f2324bfd461 to your computer and use it in GitHub Desktop.
Save anonymous/f8d6fc6544be4e04df598f2324bfd461 to your computer and use it in GitHub Desktop.
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)) {
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