Initiate file download with Koa
You should be able to simple set this.body
to the file stream
this.body = fs.createReadStream(__dirname + '/test.zip');
then set the response headers as appropriate.
this.set('Content-disposition', 'attachment; filename=' + filename);
this.set('Content-type', mimetype);
For anyone else who sees this in the future, it's worth mentioning that there is a built in attachment
method on the response
object that you can use to set the Content-Disposition
to attachment
with a specified filename. So you can do this:
this.attachment('hello.txt')
And it would be the same thing as the following:
this.set('Content-disposition', 'attachment; filename=hello.txt')
For Koa 2:
ctx.attachment('hello.txt')
Bit of a different file download example with error checking, using Node with Koa 2. I am not sure if it is necessary to destroy the stream afterwards as described here https://github.com/jshttp/content-disposition#options
router.get('/downloads/:version/:file', async function(ctx) {
const fileName = `${__dirname}/downloads/${ctx.params.version}/${ctx.params.file}`;
try {
if (fs.existsSync(fileName)) {
ctx.body = fs.createReadStream(fileName);
ctx.attachment(fileName);
} else {
ctx.throw(400, "Requested file not found on server");
}
} catch(error) {
ctx.throw(500, error);
}
});
In browser sample: https://myserver.com/downloads/1.0.0/CoolAppFile.zip