MongoDB
 sql >> Datenbank >  >> NoSQL >> MongoDB

wie man eine in gridFS gespeicherte Datei mit nodeJS herunterlädt

Hoffe, das hilft!

exports.getFileById = function(req, res){
var role = req.session.user.role;
var conn = mongoose.connection;
var gfs = Grid(conn.db, mongoose.mongo);
gfs.findOne({ _id: req.params.ID, root: 'resume' }, 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: req.params.ID,
      root: 'resume'
    });

    readstream.on("error", function(err) { 
        res.end();
    });
    readstream.pipe(res);
  });
};