Digvijay
Digvijay

Reputation: 3271

How to upload image using Base64 string in NodeJs

I am trying to upload image on server as I am getting base64 string when user is uploading image from an android app though I am getting that base64 string on backend but how can I convert it into image and save it into some directory.

Below is my code:

server.js

const express = require('express');
const app = express();

const port = process.env.PORT || 3000;

app.use(require('./routes/upload'));

app.listen(port, console.log(`App is running at ${port} port.`));

upload.js

const express = require('express');
const router = express.Router();

router.use(express.json());
router.use(express.urlencoded({extended:true}));

router.post('/upload',(req,res) => {

   const name = req.body.base64Image;
   console.log(name);
});

module.exports = router;

Someone let me know how can I achieve desired result.

Upvotes: 0

Views: 8302

Answers (2)

Denys Levshenkov
Denys Levshenkov

Reputation: 284

You can use fs to save base64 line to image file

fs.writeFileSync(path.join(uploadPath, fileName), new Buffer(base64, 'base64'))

Upvotes: 2

proxim0
proxim0

Reputation: 1538

You need to create a buffer

const base64Data = new Buffer.from(req.body.base64data.replace(/^data:image\/\w+;base64,/, ""), 'base64');

Then should be able to save or upload to s3 etc

Upvotes: 2

Related Questions