gaurav tyagi
gaurav tyagi

Reputation: 21

NodeJS: streaming multiple files from readstream (gridFS) to show on frontend

I have uploaded multiple image files into MongoDB using "Multer" and "multer-gridfs-storage". I want to extract these files and show them as thumbnails on the webpage. I have tried to extract these files into ReadStream and storing them into an array which i can loop.

var streams = [];
    console.log(result)
    for (var i = 0; i < result.length; i++) {

        var gfs = Grid(conn.db);
        var campground = gfs.createReadStream({
            _id: result[i]._id
        });
        streams[i] = campground;
        console.log("   " + i);
    }

I want to pass these to the front end where they can be displayed, but they are not displaying. I tried running the following code in loop.

    var rest
    streams[0].pipe(rest)
    res.writeHead(200, { 'Content-Type': 'image/jpeg' });
    res.write(rest);
    //      res.addTrailers({ 'image/jpeg': rest });
    res.end();

is not working. The following works but only displays one file

 streams[i].pipe(res)

I want to pass the array of images to my ejs file. The streams[i] array is grid object and not the final images. How do i accomplish this?

Regards, Gaurav

Upvotes: 0

Views: 2204

Answers (2)

Johnny Santana
Johnny Santana

Reputation: 157

Don't know if you're still looking, but here what I'm using:

var gfs = Grid(req.conn.db, mongoose.mongo);
var fileId = new mongoose.Types.ObjectId();
var fileName = file.filename;

//Create a gridfs-stream into which we pipe multer's temporary file saved in uploads
var writestream = gfs.createWriteStream({
    _id: fileId,
    filename: file.originalname,
    aliases: fileName
});

//Pipe multer's temp file /uploads/filename into the stream we created above.
fs.createReadStream(imgDir + fileName)
    .on("end", function () {
        // something
    })
    .on("err", function () {
        var msg = 'Erro enviando imagem para o  banco de dados';
        req.flash('error_msg', msg);
    })
    .pipe(writestream);

Upvotes: 0

gaurav tyagi
gaurav tyagi

Reputation: 21

Got the answer after some searching

    const bufs = [];
    readstream.on('data', function(chunk) {
        bufs.push(chunk);
    });
    readstream.on('end', function() {
        const fbuf = Buffer.concat(bufs);
        res.setHeader('Content-Type', 'image/jpeg');
        res.writeHead(res.statusCode);
        res.write(fbuf);
        /res.end();

    });

Upvotes: 2

Related Questions