,

Uploading and displaying images in React.js with MongoDB and Node.js: Converting images to base64 and retrieving them from MongoDB

Posted by






How to upload and display images in React, MongoDB, and Node.js

How to upload and display images in React, MongoDB, and Node.js

In this article, we will discuss how to upload images to a MongoDB database using a Node.js server and then display those images in a React.js frontend. We will also cover how to convert the images to Base64 format for storage and retrieval.

Upload Images to MongoDB using Node.js

First, let’s create a Node.js server using Express to handle the image upload functionality. We will use Multer middleware to handle the file upload process. Here’s an example of how to do this:


const multer = require('multer');
const storage = multer.diskStorage({
destination: function(req, file, cb) {
cb(null, 'uploads/');
},
filename: function(req, file, cb) {
cb(null, file.fieldname + '-' + Date.now() + '.' + file.originalname.split('.').pop());
}
});
const upload = multer({ storage: storage });

app.post('/upload', upload.single('image'), (req, res) => {
const file = req.file;
if (!file) {
return res.status(400).send('Please upload a file.');
}
// Save file to MongoDB database
// ...
res.send('File uploaded successfully.');
});

Display Images in React.js using Base64

Once the images are uploaded to the MongoDB database, we can retrieve and display them in a React.js frontend. To do this, we need to fetch the image data from the server and convert it to Base64 format for display. Here’s an example of how to achieve this:


import React, { useState, useEffect } from 'react';

const ImageDisplay = () => {
const [image, setImage] = useState('');

useEffect(() => {
fetch('/get-image') // Replace with actual API endpoint
.then(response => response.json())
.then(data => {
setImage(data.image);
});
}, []);

return (
Uploaded image
);
};

export default ImageDisplay;

Conclusion

Uploading and displaying images in a React, MongoDB, and Node.js application is a common requirement for many web applications. By using the techniques outlined in this article, you can easily implement image upload and display functionality in your own projects.


0 0 votes
Article Rating
25 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Ayush Goel
1 year ago

please make another vidoe if i wanna store it on large scale?

apple lemon
1 year ago

bro i got error Status Code:413 Payload Too Large, when i upload how can i fix this ?

Murat Yağcı
1 year ago

thanks

Invest and Cycle Cheap
1 year ago

do you know a way to compress these on the backend? I am trying to do the same thing but my file size is ~4 mb or so for each file. It would be awesome if I could shrink it down. I unfortunately have to use PNG type because I need my background transparent

Prime Finds
1 year ago

how to do the same for react native?

marvel world 🍿
1 year ago

Thanku man ❤️

one three zero five
1 year ago

after adding moer than 20 product it become very slow

Victor Temple
1 year ago

i want to thank you so much for this explanation. it help me a lot!

Vitor Santos
1 year ago

pls help me!!!, how can i showing off these images in my handlebars-html( it´s does wrong).

app.post("/Data",(req,res)=>{

const novaPostagem = {

titulo:req.body.titulo,

descricao:req.body.descricao,

comentario:req.body.comentario,

image:req.body.image

}

new Postagens(novaPostagem).save().then(()=>{

console.log("salva com sucesso!!!"+ req.body.image)

}).catch((err)=>{

console.log("erro ao salva:"+err)

})

})

{{#each Postagem}}

<div class="card mt-2">

<ul>

<a href=""><li>{{titulo}}</li></a>

<small>{{descricao}}</small>

</ul>

<hr>

<img src="{{image}}" alt="image" style="width: 200px;">

</div>

{{else}}

<div class="card">

<h4>nada encontrado!!!</h4>

</div>

{{/each}}

the image code is save this form in my mongodb:

image: BinData(0, 'bGy9nuyubzIuc99G5n')

MAINAK MUKHRJEE
1 year ago

Thanks man this helped a lot

Zakaria Elharchi
1 year ago

please , is that can work for excel files?

SUPRATIK SARKAR
1 year ago

when i logout form the account, the image gets deleted.

Ayush
1 year ago

Amazing explanation

Ayush
1 year ago

brother pls make video on most efficient image storing

Mathew Uy
1 year ago

awesome tutorial new subscriber here, the upload use cases in your channel are awesome, God bless you

Huy Thái
1 year ago

i don't quite understand the base64 to image conversion, base 64 will be automatically converted back to the image upon transfer and the src attribute of the img tag?

Abdulmomin
1 year ago

CORS error on Base64 images with large image size how to fix it

Abdulmomin
1 year ago

CORS error on Base64 images with large image size how to fix it

Abdulmomin
1 year ago

CORS error on Base64 images with large image size

Ameer Ibrahim
1 year ago

Thank you