0

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.

2 Answers 2

2

You can use fs to save base64 line to image file

fs.writeFileSync(path.join(uploadPath, fileName), new Buffer(base64, 'base64'))
1
  • 1
    For TypeScript developers, new Buffer has been deprecated. Buffer.from should be used instead
    – Hiroki
    Commented Nov 1, 2022 at 5:45
2

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

2
  • I want to save this image in upload directory so how can I give it a path to upload. Commented Aug 4, 2021 at 14:52
  • If you want that, you can use multer Commented Jul 11, 2022 at 15:42

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.