javascriptnode.jsdownloadkoakoa-router

Trigger a download in Koa request handler


I'm trying to trigger a download from a POST request handler in Koa with koa-router. Essentially, I'm trying to do something like this:

app.js

const Koa = require('koa')
const router = require('./router')

const app = new Koa()

app.use(router.routes())
app.use(router.allowedMethods())

app.listen(3000)

router.js

const fs = require('fs')
const Router = require('koa-router')

const router = new Router()

router.post('/generate', function * () {
  const path = `${__dirname}/test.txt`
  this.body = fs.createReadStream(path)
  this.set('Content-disposition', 'attachment; filename= test.txt')
})

module.exports = router

client.js

const { fetch } = window;

const request = {
  method: 'POST',
  body: JSON.stringify({ fake: 'data' })
}

// Make the POST request
fetch('/generate', request)

However, when the POST request is sent, nothing happens. I don't get any error in the server console or the browser console either. Any help would be appreciated!


Solution

  • You could try using https://github.com/koajs/send

    router.post('/generate', function * (next) {
        yield send(this, 'file.txt');
    });
    

    And in client side, you'll need to create and trigger download upon receiving file content via post request. Put this code in request callback

    fetch('/generate', request)
      .then(res => { return res.text() })
      .then(content => {
    
        uriContent = "data:application/octet-stream," + encodeURIComponent(content);
    
        newWindow = window.open(uriContent, 'somefile');
    
      });