Node.js显示来自Mongo的GridFS的图像

时间:2012-05-14 18:21:36

标签: node.js mongodb gridfs

我有一个使用Mongo和GridFS存储图像的nodejs应用程序。我正试图通过Node.js(使用快速框架)将这些图像显示到浏览器。

我目前正在使用:

            res.writeHead(200, {'Content-Type': 'image/jpeg' });
            res.end(imageStore.currentChunk.data.buffer, 'binary');

imageStore是创建新GridStore并调用gridStore.open(...)后的gridStore对象

       var gridStore = new GridStore(self.collection.db, doc._id, doc.filename, 'r', {
            chunk_size: doc.chunkSize
        });
        gridStore.open(callback);

我确定这不是正确的方法,它会显示损坏的图像。有什么建议吗?

谢谢!

编辑:

更新到mongodb native 1.0.2后,我正在尝试使用:

来传输数据
res.contentType("image/jpeg");
var imageStream = imageStore.stream(true);
imageStream.pipe(res);

imageStore是使用gridStore.open(function(err, imageStore){ })

后的对象

2 个答案:

答案 0 :(得分:5)

确保您使用驱动程序的1.0.1并使用http请求的管道来传输数据,下面的示例是将其用于文件。在1.1中它将变得更好,因为gridstore对象将是读/写流兼容对象:)

/**
 * A simple example showing how to pipe a file stream through from gridfs to a file
 *
 * @_class gridstore
 * @_function stream
 * @ignore
 */
exports.shouldCorrectlyPipeAGridFsToAfile = function(test) {
  var db = new Db('integration_tests', new Server("127.0.0.1", 27017, 
   {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser});

  // Establish connection to db  
  db.open(function(err, db) {
    // Open a file for writing
    var gridStoreWrite = new GridStore(db, "test_gs_read_stream_pipe", "w", {chunkSize:1024});
    gridStoreWrite.writeFile("./test/gridstore/test_gs_weird_bug.png", function(err, result) {      
      // Open the gridStore for reading and pipe to a file
      var gridStore = new GridStore(db, "test_gs_read_stream_pipe", "r");
      gridStore.open(function(err, gridStore) {
        // Grab the read stream
        var stream = gridStore.stream(true);
        // When the stream is finished close the database
        stream.on("end", function(err) {          
          // Read the original content
          var originalData = fs.readFileSync("./test/gridstore/test_gs_weird_bug.png");
          // Ensure we are doing writing before attempting to open the file
          fs.readFile("./test_gs_weird_bug_streamed.tmp", function(err, streamedData) {
            // Compare the data
            test.deepEqual(originalData, streamedData);

            // Close the database
            db.close();
            test.done();          
          });
        })

        // Create a file write stream
        var fileStream = fs.createWriteStream("./test_gs_weird_bug_streamed.tmp");
        // Pipe out the data
        stream.pipe(fileStream);
      })
    })
  });
}

答案 1 :(得分:0)

env:express(3.0),mongodb-native-driver(1.2),mongodb(2.2)

gs - GridStore.writeFile之后的文件信息

res - 表达响应对象

monogodb.GridStore.read(db, gs["_id"], function(err, data) {

  res.setHeader('Content-Type', gs.contentType);
  res.setHeader('Content-Length', gs.length);
  res.setHeader('Content-Disposition', 'inline; filename="' + gs.filename + '"');

  res.end(data);

});