Reputation: 1519
I would like to know if its possible to download a file directly from the browser on a GET request.
I have a node.js API that I'm using to serve some files, and what I want is to directly download them when I make a get request to the resource from my browser. If its possible, what do I have to send? The full binary, pipe the response...? It's a bit confusing to me.
server.js
app.get('/document', async (req, res) => {
const { filename } = req.query;
const filepath = `${os.tmpdir()}/${filename}`
try {
var file = fs.readFileSync(filepath);
return res.status(200).send({ msg: 'File read successfully', file: file })
} catch (err) {
return res.send({ msg: 'Problem reading file.', err: err.toString() })
}
})
Upvotes: 0
Views: 1366
Reputation: 1519
Found two ways to solve the problem;
1.Using res.download method from express
try {
return res.download(filepath [, filename])
} catch (err) {
return res.send({ err: 'Problem reading file.', msg: err.toString() })
}
- Sending the binaries and a special header
try {
var file = fs.readFileSync(filepath);
res.setHeader('Content-disposition', `attachment; filename=${filename}`);
return res.status(200).send(file)
} catch (err) {
return res.send({ err: 'Problem reading file.', msg: err.toString() })
}
Upvotes: 1