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()
})
CodePudding user response:
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
CodePudding user response:
If we want to send file directly to client without writing to disk, use this:
backend
router.get('/download', (req, res) => {
res.set('Content-disposition', `attachment; filename="your_file_name.svg"`);
res.set('Content-Type', 'image/svg xml');
bucket.openDownloadStreamByName('your_file_name.svg').pipe(res);
})
frontend
fetch('http://localhost:8000/download')
.then(res => res.blob())
.then(data => {
saveAs(data, 'your_file_name.svg');
})