Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a file buffer to <img> tag src?

I'm developing an app using Node.js as back end and react as my fronted. Right now I created a route which upload a file and store it as a buffer type in mongodb. My question is how can I use this data when I receive it in my react app to convert it as a source prop in an html image tag? When I look at the mongodb compass the file property looks like this:(very long strings)

enter image description here When I look at the object itself when I get it as a response is looks like this:(array of numbers); enter image description here

I tried to use

  <img
      src={`data:${props.images[0].mimetype};base64,${props.images[0].file.data}`}
    />

but it did not work..

enter image description here

really appreciate if some could have an answer!

mongoose model:

   images: [
    {
    file: { type: Buffer },
     filename: { type: String },
    mimetype: { type: String }
   }
  ]

node.js

 var multer = require('multer');

 var upload = multer({
 limits: {
  fileSize: 1000000
}
});

 app.post('/upload', upload.single('file'), async (req, res) => {
 try {
 const file = {
  file: req.file.buffer,
  filename: req.file.originalname,
  mimetype: req.file.mimetype
};
// console.log(req.file.buffer.toString('base64'));
const product = new Product({ ...req.body });
product.images = [file];
await product.save();
res.status(201).send({ success: true, product });
...

app.get('/api/products/:id', async (req, res) => {
try {
const product = await Product.findById({ _id: req.params.id }).populate(
  'brand'
);

if (!product) {
  throw new Error('Cannot find the requested product');
}
res.send({ product });
....
like image 390
hindi1991 Avatar asked Oct 23 '25 14:10

hindi1991


1 Answers

Convert it to base64string like this

  <img
      src={`data:${props.images[0].mimetype};base64,${Buffer.from(props.images[0].file.data).toString('base64')}`}
    />

like image 73
Jasper Bernales Avatar answered Oct 25 '25 03:10

Jasper Bernales