Converting image-file into base64 in express nodejs

I am trying to convert an image file into base64, so I can store in base64 string form in mongoDB.

This is how I am trying to do that:'/file_upload',function(req,res){

  function base64_encode(file) {
    var bitmap = fs.readFileSync(file);
    return new Buffer(bitmap).toString('base64');

  var ImageFileToSave =  base64_encode(req.body.file);



On Client side:

<form action="/file_upload" method="POST" enctype="multipart/form-
<input type="file" name="file" />
<input type="submit" value="Upload File" />

This is the error that I am getting

TypeError: path must be a string or Buffer

how can I convert that image file(eg:image.jpg) into base64?

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

You will need to use Multer middleware to handle multipart/form-data.

const express = require('express')
const multer  = require('multer')
const upload = multer({ dest: 'uploads/' })

const app = express()'/file_upload', upload.single('example'), (req, res, next) => {
  // req.file is the `example` file or whatever you have on the `name` attribute: <input type="file" name="example" />
  // I believe it is a `Buffer` object.
  const encoded = req.file.buffer.toString('base64')

2018-10-24: See David’s comment below.

2019-06-11: Fixed example based on comments. It is indeed req.file.buffer:

Solution 2

As the previous answer wasn’t working for me, I’m sharing this other one that worked.
I made with the multer library getting the file and then transforming it to base64

const multer  = require('multer')
const upload = multer({});'/uploadlogo', upload.single('logo'), (req, res, next) => {
    // encoded has the base64 of your file
    const encoded = req.file.buffer.toString('base64');

Solution 3

you can also do it manually in a way if you want more control. here is an example but you can implement it in any way you want, as middleware or as a function to call alone.

this is assuming your image is base64 which would be "req.body.image".

var ImageMiddleware =  (req, res, next)=> {
  if (req.body.image && req.body.foldername && req.body.filename){
    const imagepath = req.body.foldername + "/" + uuidv4() + "_" + req.body.filename;

      function buff(data) {
        const base64 = data.split(',')[1];
        let buff = Buffer.from(base64, 'base64');
        return buff

      fs.writeFileSync(imagepath, buff(req.body.image))


Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply