Send files in Koa


attachment file koa Tutorials

Koa.js framework provides the response.attachment method to prompt file for download on the client.

This method creates an attachment Content-Disposition header to make this possible.

Example:

ctx.attachment('./file.json');

A simple application that sends package.json:

const Koa = require('koa');
const cors = require('@koa/cors');

const app = new Koa();
app.use(function(ctx) {
    ctx.status = 200;
    return ctx.attachment('./package.json');
});

app.listen(3000, () => console.log('Server is works'));

We should set status or body to create minimum data for the response.

The second argument of .attachment method its an object. It supports the next values:

  • fallback - string or boolean Examples:

    ctx.attachment('file.json', { fallback: 1 });
    ctx.attachment('file.json', { fallback: false });
    ctx.attachment('file.json', { fallback: 'another name.json' });
    
  • type - string

    ctx.attachment('file.json', { type: 'inline' });
    
comments powered by Disqus