Reputation: 3271
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
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
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