Display image through a html img tag stored in GridFS using Node JS

297 Views Asked by At

I had stored some images in grid FS using Node JS. Now I want to display those images in a html img tag. What should I do in the nodejs part for getting display that image? What should I give the value of src attribute of img tag?

1

There are 1 best solutions below

0
On

Firstly you should have an end point in your server where you serve images dynamicaly by an param, let say on http://localhost:8000/images/:filename

You could retrieve the image as GridFSBucketReadStream and pipe the response object but befor doing that you need set the content type to a image type.


const midleware = response => {

  const readStream = gridfs.openDownloadStreamByName(req.params.filename);

  // Asuming the image stored is of jpg type
  // Or you could retrieve the image type dynamicaly 
  res.contentType("image/jpg");

  readStream.pip(response);
}