Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save eftakhairul/6beee5b5aff76dc23df82e0f7ceb5276 to your computer and use it in GitHub Desktop.
Save eftakhairul/6beee5b5aff76dc23df82e0f7ceb5276 to your computer and use it in GitHub Desktop.
Nodejs file download
const fileDownload = (req, res, next) => {
const requestedFileName = `${req.params.id}:${req.params.filename}`;
const filePath = path.join([req.app.get('basedir'), 'storage'].join('/') , requestedFileName);
if (!fileSystem.existsSync(filePath)) {
return res.status(403).send({error: 'FileNotExists'}).end();
}
const stat = fileSystem.statSync(filePath);
const filename = path.basename(filePath);
const mimetype = mime.getType(filePath);
res.setHeader('Content-disposition', 'attachment; filename=' + filename);
res.setHeader('Content-type', mimetype);
const readStream = fileSystem.createReadStream(filePath);
readStream.pipe(res);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment