Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
64
rated 0 times [  67] [ 3]  / answers: 1 / hits: 22803  / 6 Years ago, tue, february 13, 2018, 12:00:00

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?


More From » html

 Answers
8

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


[#55171] Saturday, February 10, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
agustindejonm

Total Points: 738
Total Questions: 84
Total Answers: 84

Location: Northern Ireland
Member since Mon, Nov 14, 2022
2 Years ago
agustindejonm questions
Fri, Jun 25, 21, 00:00, 3 Years ago
Fri, Sep 18, 20, 00:00, 4 Years ago
Sat, May 16, 20, 00:00, 4 Years ago
;