Reputation: 121
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
Upvotes: 1
Views: 5871
Reputation: 2335
This worked for me:
ctx.set('Content-disposition', `attachment; filename=${fileName}.csv`);
ctx.statusCode = 200;
ctx.body = data;
Upvotes: 1
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