This is my model in MongoDB
image: {
data: Buffer,
contentType: String,
}
And i was able to display it in the backend with EJS like this
<% images.map(image => { %>
<div>
<img src="data:image/<%=image.image.contentType%>;base64,
<%=image.image.data.toString('base64')%>" alt="Image" style="width:120px;height:120px">
</div>
<% }) %>
However when i try to display the image in the frontend with reactjs i cant, this is what i’ve been trying
const [ images, setImages ] = useState([]);
useEffect(() => {
api.getImages()
.then(res => setImages(res.data))
},[])
return(
<Fragment>
{images.map(image => (
<div key={image._id}>
<ul>
<li><img src={`data:image/jpeg;base64,${image.image.data.data}`}/></li>
</ul>
</div>
))}
</Fragment>
)
};
Advertisement
Answer
I would start with this mongo document:
image: { url: String }
Then you can treat the image everywhere as a simple string, no need to decode, no binary on the database.