I'm trying to display images stored in mongoDB through GridFS. I don't quite understand it's implementation.
Here's the route to get the image:
router.post("/image", async (req, res) => {
let { filename } = req.body
const image = await gfs.files.findOne({ filename: filename });
try{
const readStream = gfs.createReadStream(image.filename);
readStream.on("error", function(err){
res.send("No image found with that title");
});
readStream.pipe(res);
} catch (err) {
res.status(500).json({error: err.message});
}
});
It's a post method because I will not be displaying the filename on the url, I plan on displaying the image on a modal from the material ui. On a button click, I will be fetching three different photos.
Here's the request, which takes the filename of the photo:
const getVerificationPicture = filename => {
return new Promise(async (resolve, reject) => {
try {
const result = await axios.post(
"http://localhost:5000/api/verifications/post/image",
filename
);
resolve(result);
} catch (error) {
reject(error);
}
});
};
I tried to save the result in variables and then use the variables to display them in an image tag, as follows:
const [images, setImages] = useState({})
const handleOpenModal = async (open, frontCardName, backCardName, faceName) => {
setOpenModal(open);
try {
const frontID = await getVerificationPicture({ filename: frontCardName });
const backID = await getVerificationPicture({ filename: backCardName });
const faceID = await getVerificationPicture({ filename: faceName });
setImages({
...images,
frontImage: frontID.data,
backImage: backID.data,
faceImage: faceID.data,
});
} catch (error) {
console.error(error);
}
};
// in the modal component
export default function RequestsModal({ open, setOpen, images }) {
return (
<Dialog open={open} onClose={() => setOpen(false)}>
...
<DialogContent>
...
<img src={images.frontImage} />
...
</DialogContent>
...
</Dialog>
);
}
However, the images were of type string, and when logged were a bunch of characters. When I try this in postman, I get the image back, but it doesn't display here. How could I display these on the img tag?