Created
May 6, 2019 18:34
-
-
Save vampaynani/04e7fd3be119fa147ed214aff899914d to your computer and use it in GitHub Desktop.
Simple Uploader
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
module.exports = { | |
PORT: process.env.PORT || 3000 | |
} |
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
require('dotenv').config(); | |
const express = require('express'); | |
const uploader = require('./uploader'); | |
const {PORT} = require('./config'); | |
const app = express(); | |
app.use(express.json()); | |
app.use(express.static('public')); | |
app.get('/', (req, res) => { | |
res.sendFile(__dirname + '/public/index.html'); | |
}); | |
app.post('/upload', uploader.fields([{name: 'photo'}]), (req, res) => { | |
if(req.files.photo){ | |
res.json({photo: req.files.photo[0].location}); | |
else{ | |
res.status(500).json({error: 'Error when uploading'); | |
} | |
}); | |
app.listen(PORT, () => `Servidor corriendo en ${PORT}`); |
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
const multer = require('multer'); | |
const slugify = require('slugify'); | |
const storage = multer.diskStorage({ | |
destination: (req, file, cb) => { | |
cb(null, 'public/uploads'); | |
}, | |
filename: (req, file, cb) => { | |
const splittedName = file.originalname.split('.'); | |
const extension = splittedName[splittedName.length - 1]; | |
const base64Name = Buffer.from(file.originalname).toString('base64'); | |
cb(null, `${base64Name}-${Date.now()}.${extension}`); | |
} | |
}); | |
module.exports = multer({ storage }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment