从GridFS的HTML中显示图像
我在上传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');