user11988937
user11988937

Reputation:

How to save base64 image using node js?

I am saving the base64 image using nodejs, it save my image at exact path, but show me the error.

Please help me to find the error.

enter image description here

Here is my code

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

const fs = require('fs');
const mime = require('mime');


const path = './uploads';

router.post('/register', (req, res, next) => {
  const base64Image = req.body.image;

  const matches = base64Image.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/);
  response = {};
  if (matches.length !== 3) {
    return new Error('Invalid input String');
  }

  response.type = matches[1];
  response.data = new Buffer(matches[2]);
  let decodedImg = response;
  let imageBuffer = decodedImg.data;
  let type = decodedImg.type;
  let extension = mime.extension(type);
  let fileName = 'image.' + extension;

  try {
    fs.writeFileSync(path + '/' + fileName, imageBuffer, 'utf8');
    return res.send({ status: 'success' });
  } catch (e) {
    next(e);
  }

  return;

});

module.exports = router;

Any solution appreciated!

Upvotes: 4

Views: 4996

Answers (1)

Sandeep Patel
Sandeep Patel

Reputation: 5148

The mistake you made is when you are creating a buffer you are not specifying an encoding. You should create buffer like this:

new Buffer() is deprecated use Buffer.from() instead.

let buff = Buffer.from(m[2],'base64'); // encoding type base64

Basic code snippet

const fs =  require('fs')
let a =  'base64ImageString'
let m =  a.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/);
  
let b =  Buffer.from(m[2],'base64');
fs.writeFile('image.png',b,function(err){
  if(!err){
    console.log("file is created")
  }
});

Also, when you writing a buffer to file you don't have to pass encoding type, but if writing string you have to.

Check this out for a demo https://repl.it/repls/GrimOfficialLocations

But it is not advised to send an image as base64 string. It is inefficient for large images. base64 roughly takes 33% more bits than its binary equivalent. I recommend you to check this out: Upload base64 image with Ajax

Upvotes: 7

Related Questions