dzm*_*dzm 2 mongodb node.js gridfs
我有一个nodejs应用程序,它使用Mongo和GridFS来存储图像.我试图通过Node.js(使用快速框架)将这些图像显示到浏览器.
我目前正在使用:
res.writeHead(200, {'Content-Type': 'image/jpeg' });
res.end(imageStore.currentChunk.data.buffer, 'binary');
Run Code Online (Sandbox Code Playgroud)
在创建新的GridStore并调用gridStore.open(...)之后,imageStore是gridStore对象
var gridStore = new GridStore(self.collection.db, doc._id, doc.filename, 'r', {
chunk_size: doc.chunkSize
});
gridStore.open(callback);
Run Code Online (Sandbox Code Playgroud)
我确定这不是正确的方法,它会显示破碎的图像.有什么建议?
谢谢!
编辑:
更新到mongodb native 1.0.2之后,我正在尝试使用以下方法来传输数据:
res.contentType("image/jpeg");
var imageStream = imageStore.stream(true);
imageStream.pipe(res);
Run Code Online (Sandbox Code Playgroud)
imageStore是使用后的对象 gridStore.open(function(err, imageStore){ })
小智 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);
})
})
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4916 次 |
| 最近记录: |