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)
When I look at the object itself when I get it as a response is looks like this:(array of numbers);
I tried to use
<img
src={`data:${props.images[0].mimetype};base64,${props.images[0].file.data}`}
/>
but it did not work..
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 });
....