gpt4 book ai didi

node.js - 显示来自 GridFS 的 HTML 图像

转载 作者:太空宇宙 更新时间:2023-11-03 22:54:55 25 4
gpt4 key购买 nike

我正在 GridFS 中上传图像,但不知道如何在 <img > 中显示它标签。

我尝试了以下代码:

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' } ]

现在这只是文件信息而不是实际的文件数据。

如何在 HTML 中显示图像?

最佳答案

您必须定义响应的内容类型,并使用数据库连接来获取数据。检查以下示例以获得一个想法:

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格式。

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

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

关于node.js - 显示来自 GridFS 的 HTML 图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22196125/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com