imageserver.js (1075B)
1 const express = require('express'); 2 const app = express(); 3 const PORT = 4200; 4 const path = require('path'); 5 const bodyParser = require('body-parser'); 6 const cors = require('cors'); 7 const fs = require('fs'); 8 const shortid = require('shortid'); 9 10 app.use(bodyParser.json()); 11 app.use(cors()); 12 13 app.get('/images/:name', (req, res) => { 14 res.sendFile(path.join(__dirname, 'images', req.params.name)); 15 }) 16 17 app.post('/image', (req, res) => { 18 const imageEncoding = req.body.imageEncoding; 19 try { 20 const base64Image = imageEncoding.split(';base64,').pop(); 21 const imageId = shortid.generate(); 22 23 fs.writeFile(path.join(__dirname, 'images', `${imageId}.png`), base64Image, {encoding: 'base64'}, function(err) { 24 console.log('File created'); 25 res.send({ imageRef: `http://localhost:${PORT}/images/${imageId}.png` }); 26 err && console.log(err); 27 }); 28 } 29 catch (e) { 30 res.sendStatus(400); 31 } 32 }) 33 34 app.listen(PORT, () => console.log(`Image server open on port: ${PORT}`))