gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 09:59:45 26 4
gpt4 key购买 nike

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

我目前正在使用:

            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){ })之后的对象

最佳答案

确保您使用的是驱动程序的 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);
})
})
});
}

关于Node.js 显示来自 Mongo 的 GridFS 的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10588872/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com