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 (
);
};
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.
please make another vidoe if i wanna store it on large scale?
bro i got error Status Code:413 Payload Too Large, when i upload how can i fix this ?
thanks
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
how to do the same for react native?
Thanku man ❤️
after adding moer than 20 product it become very slow
i want to thank you so much for this explanation. it help me a lot!
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')
Thanks man this helped a lot
please , is that can work for excel files?
when i logout form the account, the image gets deleted.
Amazing explanation
brother pls make video on most efficient image storing
awesome tutorial new subscriber here, the upload use cases in your channel are awesome, God bless you
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?
CORS error on Base64 images with large image size how to fix it
CORS error on Base64 images with large image size how to fix it
CORS error on Base64 images with large image size
Thank you