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()
})
2
Answers
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.
Good Luck!
Also visit this Download a file from NodeJS Server using Express
If we want to send file directly to client without writing to disk, use this:
backend
frontend