Created
June 22, 2018 04:28
-
-
Save eftakhairul/6beee5b5aff76dc23df82e0f7ceb5276 to your computer and use it in GitHub Desktop.
Nodejs file download
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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