javascriptnode.jsmongodbexpressgridfs

Mongodb and Gridfs file download


I'm building an application that allows the user to upload and download files. The issue i'm currently having is that I can retrieve the file from my MongoDB database and download it locally through my machine, but I can't get it to download through the browser.

So far I have tried doing it like this

const conn = mongoose.createConnection(process.env.URL, {
    useNewUrlParser: true,
    useUnifiedTopology: true
})

const bucket = new GridFSBucket(conn, {bucketName: 'uploads'});


router.get('/download', (req, res) => {

    const files = bucket.openDownloadStreamByName('3987a162969935378c4f8cbe5d95bb46.svg').pipe(fs.createWriteStream('./3987a162969935378c4f8cbe5d95bb46.svg'))
    res.end()
})

Solution

  • I do not think the issue is with mongoDB or Gridfs its how you are dealing with the file stream. If you want the file to be downloaded once the user calls /GET /download you need to
    use - res.download(file); e.g.

    const conn = mongoose.createConnection(process.env.URL, {
      useNewUrlParser: true,
      useUnifiedTopology: true
    })
    
    const bucket = new GridFSBucket(conn, {
      bucketName: 'uploads'
    });
    
    
    router.get('/download', (req, res) => {
    
      const files = bucket.openDownloadStreamByName('3987a162969935378c4f8cbe5d95bb46.svg').pipe(fs.createWriteStream('./3987a162969935378c4f8cbe5d95bb46.svg'))
      res.download(files)
    })

    Good Luck! Also visit this Download a file from NodeJS Server using Express