Created
January 30, 2017 12:39
-
-
Save davidep87/fc2c4216139467ca38f92d8ce3da6da4 to your computer and use it in GitHub Desktop.
Stream a file from a private directory in NodeJS with KoaJS
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 fs = require('fs'); | |
| const path = require('path'); | |
| /** | |
| * @param ctx - Koa context (this) (required) | |
| * @param file - contain file information (required) | |
| * @param file.fileType - contain file type information such as application/pdf || image/jpg and so on.. | |
| * @param file.filePath - contain the private file path | |
| */ | |
| function* viewFile(ctx, file){ | |
| let fileType = file.fileType; | |
| fileType = fileType.split("/"); | |
| let fileTypeSplitCount = fileType.length; | |
| fileType = fileType[fileTypeSplitCount-1]; | |
| let result = {}; | |
| let stat = fs.statSync(path.join(__dirname, '../'+file.filePath)); | |
| ctx.set('Content-Type', `${file.fileType}`); | |
| ctx.set('Content-Disposition', `inline; filename=${file.filePath}`); | |
| ctx.set('Connection', 'keep-alive'); | |
| ctx.set('Content-Transfer-Encoding', 'binary'); | |
| ctx.set('Accept-Ranges', 'bytes'); | |
| ctx.set('Content-Length', stat.size); | |
| result.file = fs.readFileSync(path.join(__dirname, '../'+file.filePath)); | |
| return result; | |
| } | |
| // Return file to stream | |
| this.body = yield viewFile(this, result); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment