首页 > 解决方案 > 使用 Node JS 通过存储在 GridFS 中的 html img 标签显示图像

问题描述

我使用 Node JS 在网格 FS 中存储了一些图像。现在我想在 html img 标签中显示这些图像。我应该在 nodejs 部分做什么来显示该图像?我应该给 img 标签的 src 属性的值是什么?

标签: node.jsmongodbgridfsgridfs-stream

解决方案


首先,您应该在服务器中有一个端点,您可以在其中通过参数动态提供图像,比如说 http://localhost:8000/images/:filename

您可以将图像检索为 GridFSBucketReadStream 并通过管道传输响应对象,但在此之前您需要将内容类型设置为图像类型。


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);
}

推荐阅读