【问题标题】:Image not display serving image using GridFS in Node.js图像不显示在 Node.js 中使用 GridFS 的服务图像
【发布时间】:2013-12-20 22:30:19
【问题描述】:

我正在从 AFNetworking 获取一个 png 文件,并将其保存到 GridFS,然后我希望能够在某个时候检索它。出于好奇,我在图像进入 GridFS 之前记录了它,它看起来像..

<89504e47 0d0a1a0a 0000000d 49484452 00000074 0000008c 08020000 0022391a   ...>

我将它保存在缓冲区中,然后将其存储到 GridFS 中。

当我通过GET 请求检索它时,我在发送它之前再次记录它,它似乎采用相同的格式。 然后我尝试这样做

res.writeHead(200, {'Content-Type': 'image/png' });
gs.createReadStream(image).pipe(res); //using GridJS this it the syntax to read

在浏览器中查看时,它看起来就像一个空的或损坏的图像链接。如果我检查页面源,它​​似乎只是

如果我从不设置标题,它只会显示为数百行

<89504e47 0d0a1a0a 0000000d 49484452 00000074 0000008c 08020000 0022391a   ...>

我觉得我没有正确转换缓冲区之类的。

【问题讨论】:

    标签: javascript node.js mongodb buffer gridfs


    【解决方案1】:
    var http = require('http'),
       MongoDB = require("mongodb"),
       MongoClient = require("mongodb").MongoClient,
       GridStore = require("mongodb").GridStore;
    
    http.createServer(function (req, res) {
        console.log("Serving request for file: " + req.url);
        MongoClient.connect("mongodb://localhost:27017/test", {}, function(err, db) {
            gridStore = new GridStore(db, req.url, "r");
            gridStore.open(function(err, gs) {
                if (err) {
                    console.log("error in open: " + err);
                    return;
                }
    
                res.writeHead(200, {'Content-Type': 'image/png'});
                var s = gs.stream(true);
                s.pipe(res);
            });
        });
    
    }).listen(8124, "127.0.0.1");
    
    console.log('Server running at http://127.0.0.1:8124/');
    

    我可以使用上面粘贴的代码成功运行服务器并将 png 文件成功地提供给浏览器。但是,既然您说当您执行“查看源”时,源的原始内容确实出现在客户端。我建议尝试我编写的代码,看看是否有同样的问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-15
      • 1970-01-01
      • 2012-05-22
      • 1970-01-01
      • 2014-04-08
      • 2017-06-23
      • 1970-01-01
      • 2016-04-27
      相关资源
      最近更新 更多