【问题标题】:Display image through a html img tag stored in GridFS using Node JS使用 Node JS 通过存储在 GridFS 中的 html img 标签显示图像
【发布时间】:2020-11-11 12:23:46
【问题描述】:

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

【问题讨论】:

    标签: node.js mongodb gridfs gridfs-stream


    【解决方案1】:

    首先,您应该在服务器中有一个端点,您可以在其中通过参数动态提供图像,比如说 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);
    }
    

    【讨论】:

      猜你喜欢
      • 2016-11-22
      • 2015-07-31
      • 2014-09-29
      • 2014-08-06
      • 1970-01-01
      • 2017-09-12
      • 1970-01-01
      • 2015-04-25
      相关资源
      最近更新 更多