Skip to content

Express js upload and save base64 image into File System

Last updated on November 17, 2022

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}!`))
1 1 vote
Article Rating
Subscribe
Notify of
guest

1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments