Code can send one image file to view, but when I want to send many files, it gives error:
Error: Can't set headers after they are sent.
app.get('/api/upload', function (req, res) {
var arr = [];
var i =0;
gfs.files.find({}, {}).forEach(function (files) {
if (files.length === 0) {
return res.status(400).send({
message: 'File not found'
});
}
arr.push(files);
res.writeHead(200, {'Content-Type': arr[i].contentType});
var readstream = gfs.createReadStream({
filename: arr[i].filename
});
arr.splice(i, 1 );
readstream.on('data', function (data) {
res.write(data);
});
readstream.on('end', function () {
res.end();
});
readstream.on('error', function (err) {
console.log('An error occurred!', err);
throw err;
});
});
});
So; How can I make the code send all images to view? One by one, or as one object?
Ps. Reason for splice is, that forEach push first item, first & second, first & second & third, etc.:
Value:
[ { _id: 5927bd80b4f177148865960d,
filename: '9m79o7R.jpg',
contentType: 'image/jpeg',
length: 796432,
chunkSize: 261120,
uploadDate: 2017-05-26T05:30:44.947Z,
aliases: null,
metadata: { objectId: '9m79o7R.jpg' },
md5: 'e58694132f00a7b5d2f623cdd45d36f6' } ]
Value:
[ { _id: 5927bd80b4f177148865960d,
filename: '9m79o7R.jpg',
contentType: 'image/jpeg',
length: 796432,
chunkSize: 261120,
uploadDate: 2017-05-26T05:30:44.947Z,
aliases: null,
metadata: { objectId: '9m79o7R.jpg' },
md5: 'e58694132f00a7b5d2f623cdd45d36f6' },
{ _id: 5927bdadb4f1771488659614,
filename: 'blue_sky-t2.jpg',
contentType: 'image/jpeg',
length: 43594,
chunkSize: 261120,
uploadDate: 2017-05-26T05:31:26.526Z,
aliases: null,
metadata: { objectId: 'blue_sky-t2.jpg' },
md5: 'feda400c51b0c37f7c3d2ba439f1c776' } ]