使用mongodb gridfs中的节点显示图像

时间:2013-11-17 10:15:37

标签: node.js mongodb

下面的代码可以在firefox中运行,但不能在IE / Chrome中运行,其中节点应用程序崩溃并显示消息“元数据未知”。

var http = require('http'),
    url = require('url'),
    path = require('path'),
    mongo =  require('mongodb') ,
    qs =  require('qs') ,
    mongoServer = mongo.Server, 
    Db = mongo.Db,
    Grid = require('gridfs-stream'),
    fs = require('fs'); 

var server = new mongoServer('127.0.0.1', 27017, {auto_reconnect: true});
var DB = new Db('my_sitebase_image', server,{safe:true});
DB.open(function(err,db){db.admin().authenticate('ident','passwd',function(err,result){}) }); 

http.createServer(function(req, res) {
var uri = url.parse(req.url).pathname;
var filename = path.join(process.cwd(), uri); 
var query = url.parse(req.url,true).query;
var image = query.image;
var gfs = Grid(DB, mongo);
//
gfs.files.findOne({ filename: query.image },function (err, file) {   
    if(file!=null){
        lastModified = file.uploadDate; 
                    // put logic here to cache to disk.
        mimeType = file.metadata.contentType; 
        //
        res.writeHead(200, {'Content-Type': mimeType});   
        //
        readstream = gfs.createReadStream({filename: query.image });
        readstream.pipe(res);  

    }else{ 
        res.writeHead(200, {'Content-Type': 'text/plain'});
        res.write('404 Not Found\n');
        res.end();
    }

})    
}).listen(1337); 

目标是更改我的php / mongo代码。 我正在考虑(如我所说的)一个favicon问题或类似的东西...... 目前,我没有成功。

非常感谢。

编辑:我添加了favicon测试,没有任何变化:

var countF = 0;
http.createServer(function(req, res) {
    countF += 1;
    console.log(countF); // IE and Chrome don't log nothin here
    if (req.url == '/favicon.ico') {
        res.writeHead(404, {'Content-type' : 'text/plain'});
        res.end('not found'); 

}else{   // ...

0 个答案:

没有答案