Created
March 1, 2019 15:54
-
-
Save fabiobusnello/dd02ed7044fd9e9e6d09560fc2eaa0a5 to your computer and use it in GitHub Desktop.
carregamento de arquivos express
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
const multer = require('multer') | |
const express = require('express') | |
const storage = multer.diskStorage({ | |
destination: (req, file, cb) => { | |
cb(null, 'files/tmp') | |
}, | |
filename: (req, file, cb) => { | |
if(['jpg','jpeg','png', 'octet-stream'].includes(file.mimetype.split('/')[1].toLocaleLowerCase())){ | |
cb(null, Date.now()+"_"+file.originalname ) | |
}else{ | |
cb('unsupported extension', null) | |
} | |
} | |
}) | |
// só aceita arquivos com no máximo 5mb | |
const upload = multer({ storage, limits: {files: 1, fileSize: 5120000} }).any() | |
const loadFields = async (req, res, next)=>{ | |
if(!req.headers['content-type'])return next() | |
const contentTipe1 = req.headers['content-type'].includes('application/xml') | |
|| req.headers['content-type'].includes('text/plain') | |
|| req.headers['content-type'].includes('application/javascript') | |
|| req.headers['content-type'].includes('text/xml') | |
|| req.headers['content-type'].includes('text/html') | |
if(contentTipe1)return next() | |
const contentTipe2 = req.headers['content-type'].includes('application/x-www-form-urlencoded') | |
|| req.headers['content-type'].includes('application/json') | |
if(contentTipe2){ | |
express.json()(req, res, next) | |
return | |
} | |
upload(req, res, next, (err)=>{ | |
if(err){ | |
errors(err, res) | |
} | |
next() | |
}) | |
} | |
module.exports = loadFields |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment