我有请求处理程序将文件从 MongoDB (GridFS) 发送到客户端,如下所示,但它使用 data
变量,因此内容在内存中。我需要在流模式下进行此操作并将文件分块发送给客户端。我无法重新识别如何通过管道
缓冲区来响应。查看第二个代码 - 它不起作用,但显示我需要的东西。
也许有用:GridFS 中的数据是 Base64 编码的,但如果流式传输可以更高效,则可能会更改。
内存版本
router.get('/get/:id', function(req,res){
getById(req.params.id, function(err, fileId){
new GridStore(db, fileId, "r").open(function(err, gridStore) {
res.set('Content-Type', gridStore.contentType);
var stream = gridStore.stream(true);
var data = '';
stream.on("data", function(chunk) {
data += chunk;
});
stream.on("end", function() {
res.send(new Buffer(data, 'base64'));
});
});
});
});
流模式版本
router.get('/get/:id', function(req,res){
getById(req.params.id, function(err, fileId){
new GridStore(db, fileId, "r").open(function(err, gridStore) {
res.set('Content-Type', gridStore.contentType);
var stream = gridStore.stream(true);
stream.on("data", function(chunk) {
new Buffer(chunk, 'base64').pipe(res);
});
stream.on("end", function() {
res.end();
});
});
});
});
更新
我想我快要解决这个问题了。我发现这有效,但不能从 Base64 解码:
new GridStore(db, fileId, "r").open(function(err, gridStore) {
res.set('Content-Type', gridStore.contentType);
gridStore.stream(true).pipe(res);
});
最佳答案
exports.sendFile = function(db, res, fileId) {
var grid = require('gridfs-stream');
var gfs = grid(db, mongoose.mongo);
var on_error = function(){
res.status(404).end();
};
var readstream = gfs.createReadStream({
filename: fileId,
root: 'r'
});
readstream.on('error', function(err) {
if (('\'' + err + '\'') === '\'Error: does not exist\'') {
return on_error && on_error(err);
}
throw err;
});
return readstream.pipe(res);
}
关于node.js - 在 Express 中将缓冲区流式传输到客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23288777/