2014-03-05 68 views
0

我正在GridFS中上传图像,但不知道如何在<img >标记中显示此图像。从GridFS以HTML格式显示图像

我尝试下面的代码:

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中显示图像?

回答

4

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

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

编辑:

所以,当你想设置的图像作为源,可以将图像(获取来自DB)的二进制数据转换为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'); 
+0

没有给出结果... u能告诉我如何让这个'image'在'html'中显示。 – Anup

+0

我在我的项目中使用了这个代码,并且测试了它。当你在mongo中使用gfs保存图像时,它将被保存为缓冲区,所以你可以使用dbconnection获取它。将内容类型指定为图像后,您可以将该内容显示为响应 – yasmuru

+0

您的代码正常工作....我正努力在我的“html页面”中显示。 – Anup