Created
September 17, 2019 03:42
-
-
Save anderjs/f75253d7230324e96bb59f80e85ca507 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 { Router } from 'express' | |
import fs from 'fs' | |
import multer, { diskStorage } from 'multer' | |
import path from 'path' | |
/** | |
* @description | |
* Allows to control all malicious content via FormData. | |
* @param {{}} file | |
* @param {function} callback | |
*/ | |
function sanitizeFile(file, callback) { | |
const audioMimeType = 'audio/' | |
const imageMimeType = 'image/' | |
const isAllowedMimeType = | |
file.mimetype.startsWith(imageMimeType) || | |
file.mimetype.startsWith(audioMimeType) | |
if (isAllowedMimeType) { | |
return callback(null, true) | |
} | |
callback('Mimetype is not allowed.') | |
} | |
const storage = diskStorage({ | |
destination: function(_req, _file, callback) { | |
return callback(null, path.join(__dirname, 'content')) | |
}, | |
filename: function(_req, file, callback) { | |
callback(null, `${Date.now()}-${file.originalname}`) | |
} | |
}) | |
const upload = multer({ | |
storage, | |
limits: { | |
fileSize: 2000000 | |
}, | |
fileFilter: function(_req, file, callback) { | |
sanitizeFile(file, callback) | |
} | |
}).single('upload') | |
const uploadRouter = Router() | |
uploadRouter.post('/', async (req, res) => { | |
upload(req, res, async err => { | |
if (err) { | |
return res.status(502).json({ | |
message: err, | |
statusCode: 502 | |
}) | |
} | |
if (!req.file) { | |
return res.status(400).json({ | |
message: 'File not found', | |
statusCode: 400 | |
}) | |
} | |
return res.status(201).json({ | |
statusCode: 201 | |
}) | |
}) | |
}) | |
uploadRouter.get('/', async (req, res) => { | |
const { filename } = req.query | |
const files = path.join(__dirname, 'content') | |
fs.readdir(files, (err, files) => { | |
if (err) { | |
return res.status(502).json({ | |
message: err, | |
statusCode: 502 | |
}) | |
} | |
const fileExist = files.includes(filename) | |
if (!fileExist) { | |
return res.status(404).json({ | |
message: `File ${filename} was not found.`, | |
statusCode: 404 | |
}) | |
} | |
const filepath = path.join(__dirname, 'content', files[files.indexOf(filename)]) | |
}) | |
}) | |
export default uploadRouter |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment