Express js upload and save base64 image into File System

const express = require('express')
const app = express()
const port = 6000
const bodyParser = require('body-parser');
const fs = require('fs');

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
 
// parse application/json
app.use(bodyParser.json());


const uploadImage = async (req, res, next) => {

    try {

        // to declare some path to store your converted image
        const path = './images/'+Date.now()+'.png'

        const imgdata = req.body.base64image;

        // to convert base64 format into random filename
        const base64Data = imgdata.replace(/^data:([A-Za-z-+/]+);base64,/, '');
        
        fs.writeFileSync(path, base64Data,  {encoding: 'base64'});

        return res.send(path);

    } catch (e) {
        next(e);
    }
}

app.post('/upload/image', uploadImage)


app.listen(port, () => console.log(`Example app listening on port ${port}!`))

I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.

DMCA.com Protection Status