我正在使用 GridFS 来检索来自mongoDB的图片:
我做:
// Connect to the db
MongoClient.connect("mongodb://10.8.2.232/mydb", function(err, db) {
if(err) return console.dir(err);
var fileId = mongoose.Types.ObjectId("542e684a8a1cec178a172671");
var gridStore = new GridStore(db, fileId, 'r');
gridStore.open(function (err, gridStore) {
//console.log(gridStore.currentChunk.data.buffer);
gridStore.read(function (error,data){
console.log(data, 'binary');
res.writeHead(200, {'Content-Type': 'image/png'});
var s = gridStore.stream(true);
console.log(s);
});
});
});
}).listen(8124, "127.0.0.1");
console.log('Server running at http://127.0.0.1:8124/');
连接到MongoDB好的 “S”显示带有关于图像的一些信息的JSON:
currentChunk:
{ file: [Circular],
writeConcern: [Object],
objectId: 542e65378a1cec1227ae2bb1,
chunkNumber: 0,
data: [Object],
internalPosition: 17959 } },
但我想显示图片:
fs.chunks:
{
"_id" : ObjectId("542e684a8a1cec1745zs3"),
"n" : 1,
"data" : BinData(0,"2N6DSSfbCN/LLacNDYrJUQDEZgimMUwFpQGoJP0RU19Bi4PM82DjrUnKhE/P9v7P8ZveD1oDpFBM0iml9NE3WQmAvYFoG+nhD73Jm4N9b4LpylaAN5Ef+gVdgGSTAfSUwOikXoVick5pSQCkRmTCU5NT9VVfjHdAx74/ZhFRj+TIRjzlAhzkACBElzgMwGCo7tX+FYrpQLJ5KRmXiwF"),
"files_id" : ObjectId("542e684a8a1cec178a172671")
}
我如何能够在浏览器中检索我的图像(数据中)?
谢谢!
答案 0 :(得分:1)
如果要传输文件,请不要使用read()
。例如:
gridStore.open(function (err, gridStore) {
if (err) {
res.writeHead(500);
return res.end();
}
res.writeHead(200, {'Content-Type': 'image/png'});
gridStore.stream(true).on('end', function() {
db.close();
}).pipe(res);
});