how to download a file saved in gridFS using nodeJS

前端 未结 2 567
长情又很酷
长情又很酷 2020-12-19 10:51

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 cont

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-19 11:14

    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 = "";
        gfs = Grid(connection.db, mongoose.mongo);
    
        gfs.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);
            }
        });
    

提交回复
热议问题