Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to download a file saved in gridFS using nodeJS

I need to download a resume from GridFS, below is the code ive written to do it, but this seems to not give me a physical file for download, this is used to reading the contents. How can i download the file?

exports.getFileById = function(req, res){
var conn = mongoose.connection;
var gfs = Grid(conn.db, mongoose.mongo);
var id = req.params.ID;
gfs.exist({_id: id,root: 'resume'}, function (err, found) {
    if (err) return handleError(err);
    if (!found)
        return res.send('Error on the database looking for the file.');
    gfs.createReadStream({_id: id,root: 'resume'}).pipe(res);
});
};
like image 988
Syed Faizan Avatar asked Oct 09 '15 10:10

Syed Faizan


People also ask

How do I download from GridFS?

There are several ways to download a file from GridFS. The two main approaches are: The driver downloads a file as a byte array or by writing the contents to a Stream provided by the application. The driver supplies a Stream object that the application can read the contents from.

How do I download a file from a node js server?

Downloading a file using node js can be done using inbuilt packages or with third party libraries. GET method is used on HTTPS to fetch the file which is to be downloaded. createWriteStream() is a method that is used to create a writable stream and receives only one argument, the location where the file is to be saved.

How do I use GridFSBucket?

Create a GridFS Bucket Create a bucket or get a reference to an existing one to begin storing or retrieving files from GridFS. Create a GridFSBucket instance, passing a database as the parameter. You can then use the GridFSBucket instance to call read and write operations on the files in your bucket: const db = client.


2 Answers

Hope this helps!

exports.downloadResume = function(req, res){
var conn = mongoose.connection;
var gfs = Grid(conn.db, mongoose.mongo);
gfs.findOne({ _id: <resumeId>, root: <collectionName> }, function (err, file) {
    if (err) {
        return res.status(400).send(err);
    }
    else if (!file) {
        return res.status(404).send('Error on the database looking for the file.');
    }

    res.set('Content-Type', file.contentType);
    res.set('Content-Disposition', 'attachment; filename="' + file.filename + '"');

    var readstream = gfs.createReadStream({
      _id: <resumeId>,
      root: '<collectionName>'
    });
    
    readstream.on("error", function(err) { 
        res.end();
    });
    readstream.pipe(res);
  });
};
like image 59
Prashanth Hegde Avatar answered Nov 15 '22 02:11

Prashanth Hegde


I took hints from accepted answer. But I had to jump through some hoops to get it working hope this helps.

const mongodb = require('mongodb');
const mongoose = require('mongoose');
const Grid = require('gridfs-stream');
eval(`Grid.prototype.findOne = ${Grid.prototype.findOne.toString().replace('nextObject', 'next')}`);

const mongoURI = config.mongoURI;
const connection = mongoose.createConnection(mongoURI);

app.get('/download', async (req, res) => {
    var id = "<file_id_xyz>";
    gfs = Grid(connection.db, mongoose.mongo);

    gfs.collection("<name_of_collection>").findOne({ "_id": mongodb.ObjectId(id) }, (err, file) => {
        if (err) {
            // report the error
            console.log(err);
        } else {
            // detect the content type and set the appropriate response headers.
            let mimeType = file.contentType;
            if (!mimeType) {
                mimeType = mime.lookup(file.filename);
            }
            res.set({
                'Content-Type': mimeType,
                'Content-Disposition': 'attachment; filename=' + file.filename
            });

            const readStream = gfs.createReadStream({
                _id: id
            });
            readStream.on('error', err => {
                // report stream error
                console.log(err);
            });
            // the response will be the file itself.
            readStream.pipe(res);
        }
    });
like image 30
Sheece Gardazi Avatar answered Nov 15 '22 04:11

Sheece Gardazi