4

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!

5
  • Shouldn't you decode base64 data before writing the file? Commented Feb 5, 2020 at 11:32
  • Can you please explain what you are trying to say @GrafiCode Commented Feb 5, 2020 at 11:35
  • 2
    Your image data is base64 encoded, right? When you write it on file, you should first decode it with atob() Commented Feb 5, 2020 at 11:36
  • Yes, you are right. Thanks Commented Feb 5, 2020 at 11:38
  • Why are you sending base64-encoded data to begin with? Commented Feb 5, 2020 at 13:15

1 Answer 1

7

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.