如何在 Node JS 中使用 Mustache 在 MongoDB 中显示存储为二进制数据的图像 [英] How to display image stored as binary data in MongoDB using Mustache in Node JS

查看:45
本文介绍了如何在 Node JS 中使用 Mustache 在 MongoDB 中显示存储为二进制数据的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个图像 (png) 文件作为二进制数据存储在我的 MongoDB 中.我的 MongoDB 架构如下所示:

I have an image (png) file stored in my MongoDB as binary data. My MongoDB schema looks like below :

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
ImageSchema = new Schema (
{ title : String,
  picture: { content: Buffer, contentType: String }
}
);

mustache 代码如下所示:

The mustache code looks like below:

var template = "{{picture.content}} <h1>{{title}}</h1>";
var rendered = Mustache.render(template, imageObject);
$('#target').html(rendered);

MongoDB 中的数据如下图,由于太长已被缩短:

The data in MongoDB looks like below, it has been shortened as it is too long:

 "picture" : {
                "contentType" : "image/png",
                "content" : BinData(0,"iVBORw0KGgoAAAANSUhEUg ...")
             }

以下是我如何使用 multer 将其存储到 MongoDB 中:

Below is how I am storing it into MongoDB using multer :

dbmodel.findOne(req.params.title, function(err, ) {
 records.picture.content = fs.readFileSync(req.files.path);
        records.picture.contentType = 'image/png';
        records.save(function (err) {
          if(!err) {
            res.send("Image is saved into MongoDB");

          } else {
            res.send(400).send();
          }
 })

有什么方法可以将这种二进制数据转换为图像,特别是将其放入 Mustache 模板中进行显示?另外请告诉我是否需要以其他方式保存图像以及如何使用 Mustache 更轻松地显示.

What is the way to convert this binary data to image and especially fit it into the Mustache template for display ? Also please let me know if the image needs to be saved in some other way and how for easier display using Mustache.

谢谢.

推荐答案

通过将二进制数据转换为 URL 然后馈送到 标签的 src-

Convert binary data into image by converting it to a URL and then feeding to src of <img> tag-

var template="<img src={{{`data:image/png;base64,${picture.content}`}}}/> <h1>{{title}}</h1>";

这篇关于如何在 Node JS 中使用 Mustache 在 MongoDB 中显示存储为二进制数据的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆