I have a html table, where I do data from MongoDB but the image has refused to show, and I’m not sure what I am doing wrong.
here is what i have done so far.
here is the js code to get the image and the data from the client and send to the backend server
app.post('/newInt_ImgUpload', upload.array('inventoryImg', 3), async (req, res) => {
//console.log(req.files);
//console.log(req.body);
const cookies = req.headers.cookie;
const jwtToken = cookies.split("=")[1].split(";")[0];
//console.log(jwtToken);
if (!jwtToken) {
console.log('app crashed at line 119: PersonalInfo');
return res.sendStatus(401);
}
const refreshToken = jwtToken;
const user = await userModel.findOne({RefreshToken: refreshToken}).exec()
if(!user) return res.sendStatus(401);
console.log('User was found');
const count = new Uint32Array(1);
try {
const inventory = await inventoryModel.create({
'UserId': user._id,
'Name': req.body.ItemName,
'DateAdded': date.format(now, 'YYYY/MM/DD HH:mm:ss').split(" ")[0],
'Price': req.body.Price,
'WeightKG': req.body.WeightKG,
'Quantity': req.body.Quantity,
'Description': req.body.Description,
'image1': {
data: fs.readFileSync(path.join(__dirname + '/uploads/' + req.files[0].filename)).toString('base64'),
contentType: req.files[0].mimetype
},
'image2': {
data: fs.readFileSync(path.join(__dirname + '/uploads/' + req.files[1].filename)).toString('base64'),
contentType: req.files[1].mimetype
},
'image3': {
data: fs.readFileSync(path.join(__dirname + '/uploads/' + req.files[2].filename)).toString('base64'),
contentType: req.files[2].mimetype
},
'Id': Math.trunc((crypto.getRandomValues(count))/1000000)
});
const result = await inventory.save();
console.log(result);
const inventoryActivitylog = await activityLogsModel.create({
'UserId': user._id,
'Date': date.format(now, 'YYYY/MM/DD HH:mm:ss').split(" ")[0],
"Time": date.format(now, 'YYYY/MM/DD HH:mm:ss').split(" ")[1],
'Status': "Inventory updated."
});
await inventoryActivitylog.save();
req.files.forEach(files => {
fs.unlink(path.join(__dirname + '/uploads/' + files.filename), (err) => {
if (err) throw err;
//console.log('Image deleted');
});
})
console.log("All images deleted")
//res.redirect('/userProfile');
res.status(200).json({ success: true, message: 'Inventory updated and images processed' });
} catch (error) {
console.log(error);
}
});
after that has been done, the code below loads each time to the page that shows the table data, but the image refuses to show and give the following error: data:image/png;base64,[object Object]
document.getElementById('allitems').addEventListener('click', async () => {
try {
const response = await fetch('http://localhost:4000/Inventory/allInventory/List', {
method: 'GET',
headers: { 'Content-Type': 'application/json' },
credentials: 'include'
})
.then(async response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
})
.then(data => {
const inventoryList = document.querySelector('.inventoryList');
// Clear any existing rows
inventoryList.innerHTML = '';
// Loop through the fetched data and create new rows
data.forEach(item => {
console.log(item);
const eachInventory = document.createElement('div');
eachInventory.classList.add('eachInventory');
const imgsrc = `data:${item.image1.contentType};base64,${item.image1.data}`;
eachInventory.innerHTML = `
<div class="itemName">
<div><img src="${imgsrc}" alt=""></div>
<div><h4>${item.Name}</h4></div>
</div>
<div class="itemDate"><h3>${new Date(item.DateAdded).toLocaleDateString()}</h3></div>
<div class="itemPrice"><h3>${item.Price.toLocaleString()}</h3></div>
<div class="itemQuantity"><h3>${item.Quantity}</h3></div>
`;
// Append the new row to the table
inventoryList.appendChild(eachInventory);
})
});
} catch (error) {
console.error('Error:', error);
}
});
Your image is saved in base64 format. Instead of storing files in db prefer storing it in any external service. If you are using AWS you can use s3 bucket or if not using s3, you may try cloudflare image services, cloudinary etc.