Skip to content

Instantly share code, notes, and snippets.

@vampaynani
Created May 6, 2019 18:34
Show Gist options
  • Save vampaynani/04e7fd3be119fa147ed214aff899914d to your computer and use it in GitHub Desktop.
Save vampaynani/04e7fd3be119fa147ed214aff899914d to your computer and use it in GitHub Desktop.
Simple Uploader
module.exports = {
PORT: process.env.PORT || 3000
}
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}`);
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