Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initiate file download with Koa

I'm using Koa as a webserver to serve my Polymer application. Upon pressing a button in the frontend localhost:3000/export is called. I would like to deliver a file-download to the client after packing the some files to a zip-archive.

How to do this in Koa.js?

Here's an example on how to do it in Express (another option would be the download-helper

app.get('/export', function(req, res){

  var path = require('path');
  var mime = require('mime');

  var file = __dirname + '/upload-folder/dramaticpenguin.MOV';

  var filename = path.basename(file);
  var mimetype = mime.lookup(file);

  res.setHeader('Content-disposition', 'attachment; filename=' + filename);
  res.setHeader('Content-type', mimetype);

  var filestream = fs.createReadStream(file);
  filestream.pipe(res);
});

I'm looking for something like this:

router.post('/export', function*(){
  yield download(this, __dirname + '/test.zip')
})
like image 952
Hedge Avatar asked Nov 02 '15 16:11

Hedge


1 Answers

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);
like image 106
James Moore Avatar answered Sep 20 '22 23:09

James Moore