Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

router.post('/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);

  console.log(ImageFileToSave);


})

On Client side:

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

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?

like image 250
Saurabh Avatar asked Feb 13 '18 08:02

Saurabh


2 Answers

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()

app.post('/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')
  console.log(encoded)
})

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

2019-06-11: Fixed example based on comments. It is indeed req.file.buffer: https://github.com/expressjs/multer/blob/master/storage/memory.js#L8

like image 150
Francisco Mateo Avatar answered Nov 16 '22 01:11

Francisco Mateo


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({});

router.post('/uploadlogo', upload.single('logo'), (req, res, next) => {
    // encoded has the base64 of your file
    const encoded = req.file.buffer.toString('base64');
});
like image 25
David Vicente Avatar answered Nov 16 '22 00:11

David Vicente