I am creating a admin application where i want to display uploaded images of product stored in database. I have uploaded images as an object id in MongoDB. But the image container in admin app displays the number of images stored in database. But the images are not displayed. I tried using absolute URL too but that doesnot work either.
Here is my code to upload images:
{productPictures.length > 0
? productPictures.map((pic, index) => (
<div key={index}>{pic.name}</div>
))
: null}
<input
type="file"
name="productPictures"
onChange={handleProductPictures}
/>
Here is the code to display images:
<label className="key">Product Pictures</label>
<div style={{ display: "flex" }}>
{productDetails.productPictures.map((picture) => (
<div className="productImgContainer">
<img src={generatePublicUrl(picture.img)} alt="" />
</div>
))}
</div>
Generate URL function looks like this:
const api ='http://localhost:2000/'
// const api = 'http://192.168.0.104:2000/'
const generatePublicUrl = (fileName) => {
return `http://localhost:2000/src/uploads/products/${fileName}`;
}
export {
api,
generatePublicUrl
};
Function to save product in database:
const createProduct= (req, res) => {
const { name, price, description, category, quantity, createdBy } = req.body;
let productPictures = [];
if (req.files.length > 0) {
productPictures = req.files.map((file) => {
return { img: file.location };
});
}
const product = new Product({
name: name,
slug: slugify(name),
price,
quantity,
description,
productPictures,
category,
createdBy: req.user._id,
});
product.save((error, product) => {
if (error) return res.status(400).json({ error });
if (product) {
res.status(201).json({ product, files: req.files });
}
});
}
The uploaded images in program looks like this:
Open image here
But the page displays blank area and filename shows undefined when inspected.
Open image here