Chu Văn Nam
Chu Văn Nam

Reputation: 121

How to download csv file with koajs

I'm using koajs as a framework for nodejs. I try to create csv data and response it to client but not working

let fields = ['code', 'status'];
let p = new Promise((resolve, reject) => {
    json2csv({data: data, fields: fields }, (err, response) => {
        if (err) {
            reject(err);
        } else {
            resolve(response);
        }
    });
});
return p.then(data => {
    let fileName = 'promotioncode-' + moment().unix();
    ctx.response.attachment(fileName + '.csv');
    ctx.response.type = 'application/ms-excel';
    ctx.body = data;
})

The response is plan text data instead of attachment file Here is response headers

Here is response body

Upvotes: 1

Views: 5871

Answers (2)

realplay
realplay

Reputation: 2335

This worked for me:

ctx.set('Content-disposition', `attachment; filename=${fileName}.csv`);
ctx.statusCode = 200;
ctx.body = data;

Upvotes: 1

davidev
davidev

Reputation: 314

If you would like to send a downloadable file attached to the body you need to create a read stream of the file.

const fs = require('fs');

ctx.set('Content-disposition', `attachment; filename=${result}`);
ctx.statusCode = 200;
ctx.body = fs.createReadStream(result);

Note: in result you have the file path

Upvotes: 4

Related Questions