从GridFS的HT​​ML中显示图像 [英] Display image in HTML from GridFS

查看:139
本文介绍了从GridFS的HT​​ML中显示图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在上传GridFS的图像,但不知道如何在&LT显示此; IMG> 标记。

I'm uploading an image in GridFS but have no idea how to display this in an <img > tag.

我尝试以下code:

conn.once('open', function () {
    var gfs = Grid(conn.db, mongoose.mongo);
    gfs.files.find({ filename: 'img1.png' }).toArray(function (err, files) {
        if (err) { console.log(err); }
        console.log(files);
    });
});

我得到的结果:

[ { _id: 5316f8b3840ccc8c2600003c,
    filename: 'img1.png',
    contentType: 'binary/octet-stream',
    length: 153017,
    chunkSize: 262144,
    uploadDate: Wed Mar 05 2014 15:43:07 GMT+0530 (India Standard Time),
    aliases: null,
    metadata: null,
    md5: '915c5e41a6d0a410128b3c047470e9e3' } ]

现在这仅仅是个文件信息不是实际的文件数据。

Now this is just the file info not the actual file data.

如何在HTML中显示图像?

How to display image in HTML?

推荐答案

您必须定义的Content-Type的响应,并使用DB连接就可以获取数据。请检查下面的例子来得到一个想法:

You have to define the Content-Type for the response, and using db connection you can fetch the data. Check the following example to get an idea:

app.get('/filelist', function(req, res) {
    var collection = db.collection('DbCollectionName');
    var da = collection.find().toArray(function(err, items) {
        console.log(items[0]);
        res.writeHead(200, {'Content-Type': 'image/png'});
        res.end(items[1].dbfileName.buffer, 'binary');
    });
});

编辑:

所以,当你想设置图像作为源,可以将图像的二进制数据(从数据库中取出)转换为Base64格式。

So when you want to set the image as the source, you can convert the binary data of the image(fetched from db) to base64 format.

var img = document.createElement('img');
img.src = 'data:image/jpeg;base64,' + btoa('your-binary-data'); //JS have btoa() function for it.
document.body.appendChild(img);

,也可以使用十六进制为base64此外,如果你的形象不支持上述

or you can use hex to base64 also if your image doesn't support above

function hexToBase64(str) {
return btoa(String.fromCharCode.apply(null, str.replace(/\r|\n/g, "").replace(/([\da-fA-F]{2}) ?/g, "0x$1 ").replace(/ +$/, "").split(" ")));
}

和称呼其为

img.src = 'data:image/jpeg;base64,' + hexToBase64('your-binary-data');

这篇关于从GridFS的HT​​ML中显示图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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