0

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' } ]
edu
  • 53
  • 7
  • Okay so why are you trying to send this content to a template view? Did we read somewhere that you can reduce http requests by base-ecoding content within the returned HTML? This is almost certainly not what you really want to do. Rather your "files" in GridFS, should be served "individually" as "files" and accessible as their own endpoint. There is this thing called a "cache" in the browser that is meant to reduce the load of these requests. So this looks like premature optimization. – Neil Lunn May 26 '17 at 06:30
  • As to the error itself, you are creating multiple streams inside a loop and there are handlers on all of them that are going to `res.end()` at different times. Not to mention writing to the same output handle. – Neil Lunn May 26 '17 at 06:32

0 Answers0