我基本上试图将文件从 MongoDb 流式传输到客户端。文件接收没有问题,但是当流结束并且我尝试发送 request.end() 时,客户端永远不会收到它。
app.post('/upload', function (req, res) {
var db = new mongo.Db('prueba', new mongo.Server("127.0.0.1", 27017));
db.open(function (err) {
if (err) return handleError(err);
var gfs = Grid(db, mongo);
console.log(req.filename);
var uploadedSize = 0,
uploadProgress = 0;
idPdf = new ObjectId(); //cliente crea un id de mongo, el cual se utilizara para traer el recurso despues
console.log(idPdf);
var grabarm = req.pipe(gfs.createWriteStream({
filename: 'test',
_id: idPdf
}));
grabarm.on("close", function () {
var tbuffer = gfs.createReadStream({filename: 'test'});
tbuffer.on('open', function () {
// This just pipes the read stream to the response object (which goes to the client)
res.setHeader('Content-disposition', 'attachment; filename=pdfmongo.pdf');
res.setHeader('Content-type', 'application/pdf');
tbuffer.pipe(res);
});
tbuffer.on('data', function (chunk) {
console.log("receiving data");
});
tbuffer.on("close", function () {
console.log("fin"); //can see it in console
res.end("ok file received");//client never sees this
});
tbuffer.on('error', function (err) {
res.end(err);
});
});
});
});
当可读流完成读取时,默认情况下,它会发出 end() 事件,该事件将调用可写流(res 流)上的 end() 事件。在这种情况下,您无需担心调用 end() 。
因此,在调用 end() 事件后,您的 res 将不再可写。因此,如果你想保持它可写,只需将 end: false 选项传递给 pipeline() 即可。举个例子:
fs.createReadStream("./image.png").pipe(res, { end: false });
,然后稍后调用 end() 事件。
顺便说一句,您应该监听“结束”事件而不是“关闭”事件来完成流,因为“关闭”并不明确意味着所有数据已被传输。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)