仅返回255kb的数据,这是gridfs中的默认块大小。然而,在mongolab中,我看到存储了多个块。所以问题只在于读取代码。这是 -
从gridfs接收并发送响应代码 -
app.get('/download/:fileid', function(req, res) {
var buffer = [];
var id = req.params.fileid;
var base64string;
var readStream = gfs.createReadStream({_id: id});
readStream.on('data', function(chunk) {
buffer.push(chunk);
});
readStream.on('end', function() {
base64string = Buffer(buffer.concat()[0]).toString('base64');
fs.writeFile("base64.txt", base64string);
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.write(JSON.stringify({body : base64string}));
res.end();
});
});
[编辑] - 进一步的分析表明我得到了所有的块。所以问题在于连接 -
base64string = Buffer(buffer.concat()[0]).toString('base64');
[编辑] - Buffer.concat()不起作用。如何从这三个缓冲区中创建单个缓冲区?
[ <Buffer ff d8 ff e0 00 10 4a 46 49 46 00 01 02 01 00 60 00 60 00 00 ff e1 0f 07 45 78 69 66 00 00 4d 4d 00 2a 00 00 00
08 00 06 01 32 00 02 00 00 00 14 00 00 ... >,
<Buffer a1 b1 42 92 56 81 43 43 5e b8 46 61 0f 96 09 c1 c4 e8 96 2b 75 52 54 21 2a 7d 46 ba c6 66 80 01 95 3c 3d a7 16
31 ed d9 56 b5 2b 91 5e 07 14 cb 2f ee ... >,
<Buffer a6 b6 92 5a 4f 1a da c9 e8 55 97 8e d1 da 4a b3 88 26 2f e5 2c 23 2a 54 10 59 1b 9e eb 35 e8 92 cc 2e da 8b 16
91 d3 e2 91 93 99 62 e0 8e a3 80 56 aa ... >,
<Buffer 71 e6 83 65 5e b0 f1 5f 61 a6 21 a3 68 83 be 72 0b 7a 7d 47 d6 d3 69 ee 59 37 92 1a de 06 8a 22 2a 3a a0 a3 1f
1a 0e 7e ec 67 3b 8f e9 c5 87 6b 41 5b ... > ]
[编辑]根据neils建议将读取流用于响应。但是我在客户端遇到语法错误。 [意外令牌]
响应代码 -
app.get('/download/:fileid', function(req, res) {
var id = req.params.fileid;
res.set('Content-Type', 'image/jpeg');
gfs.createReadStream({_id: id}).pipe(res); });
客户代码 -
download() {
this._http.get('http://localhost:9000/download/' + this._fileid)
.map(response => response.json())
.subscribe(
data => {
console.log(data);
//this.image = data.body;
},
err => console.log('Error is..:' + err)
);;
}