node.js - 使用 Node JS 通过存储在 GridFS 中的 html img 标签显示图像
问题描述
我使用 Node JS 在网格 FS 中存储了一些图像。现在我想在 html img 标签中显示这些图像。我应该在 nodejs 部分做什么来显示该图像?我应该给 img 标签的 src 属性的值是什么?
解决方案
首先,您应该在服务器中有一个端点,您可以在其中通过参数动态提供图像,比如说 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);
}
推荐阅读
- java - “Public static final”安全漏洞的解决方案
- flutter - flutter - 需要扩展 State 和 FormField
- python - 遵循 Head First Python 2nd edition 时出现 Pytest-pep8 问题
- javascript - 当我使用 axios 发布时,Req.body 为空,但是当我使用“请求”时,它工作正常
- r - 无法在 R-studio 中读取 Excel 文件
- jsf - 单击后禁用 a4j:commandButton
- python - 我收到此错误:“UnboundLocalError:分配前引用的局部变量'Requesting_books'”
- crystal-reports - 使用 Oracle 的 Crystal 报表中缺少右括号
- c++ - 在多图中搜索一系列键
- java - 如何创建包含来自目标/生成源的类的 Spring Boot fat JAR