How can I access image files in MongoDB and send them to the client using Express.js How can I access image files in MongoDB and send them to the client using Express.js express express

How can I access image files in MongoDB and send them to the client using Express.js


Your code have an logic error. when res.end() is called, express ends the response process in the first image, your loop does not reach the next iteration.Also you cannot have multiple responses for one request. But you can send the Buffer array with JSON representation using res.json(images).

In the client, to display the images received as buffers from the server: you need to convert them to the original format doing this:

// server responseconst images = response.map(buffer => {  const rawBuffer = buffer.toString("base64");  const imageSrc = "data:image/png;base64," + rawBuffer;  const image = document.createElemment("img");  image.src = imageSrc;  return image;})/* In this method you can control how you will show the images in the client (to test, just append to any div)*/

Or, if you just want to display the images without any manipulation try this:

app.get("/showallimages", (req, res) => {    Image.find({}).exec((error, records) => { // Image is the database schema model.         var img1 = Buffer.from(records[0].img.data, "base64"); // First image coming from MongoDB.        var img2 = Buffer.from(records[1].img.data, "base64"); // Second image coming from MongoDB.        var images = [img1, img2];        const formatedImages = images.map(buffer => {          return `<img src="data:image/png;base64,${buffer.toString("base64")}"/>`        }).join("")                res.send(formatedImages)    })})