Download a csv file

73 views
Skip to first unread message

kar...@bluepi.in

unread,
Apr 27, 2015, 2:42:09 PM4/27/15
to loopb...@googlegroups.com
Hi,

How can download a csv in a remote method? The GET method i had written gives me a csv but but a file,but the file doesn't have a .csv extension.How can i resolve that?Below is the snippet


MyCollection.remoteMethod('csv', {
    accepts: {
      arg: 'where',
      type: 'object'
    },
    returns: {
      arg: 'rows',
      type: '[array]'
    },
    http: {
      verb: 'get'
    }

  });


MyCollection.afterRemote('csv', function(ctx, next) {
    // FIXME: use a proper CSV formatter that can escape string values containing "," characters
    var csv = ctx.result.rows.map(function(r) {
      return r.join(',');
    }).join('\n');
    ctx.res.header('Content-Type', 'text/csv');
    ctx.res.send(csv);
    // next() must not be called!
  });

 Order.csv = function(where, cb) {

}

Thanks,
Karabi

Miroslav Bajtoš

unread,
Apr 28, 2015, 3:49:19 AM4/28/15
to loopb...@googlegroups.com
The easiest solution is to call res.attachment:

var csv = ctx.result.rows.map(function(r) {
  return r.join(',');
}).join('\n');

ctx.res.attachment('rows.csv');
// Content-Disposition: attachment; filename="rows.csv"
// Content-Type: text/csv

ctx.res.send(csv);
// next() must not be called!

Alternatively you can set the Content-Disposition header yourself, for example:

var csv = ctx.result.rows.map(function(r) {
  return r.join(',');
}).join('\n');
ctx.res.header('Content-Type', 'text/csv');
ctx.res.header('Content-Disposition', 'inline; filename=rows.csv');
ctx.res.send(csv);

When you send the disposition "attachment", browser will immediately offer download. With the disposition "inline", the browser will try to render the result (probably as a plain text).

Miroslav

kar...@bluepi.in

unread,
Apr 28, 2015, 3:50:55 AM4/28/15
to loopb...@googlegroups.com
Thanks. I had found the solution...
Reply all
Reply to author
Forward
0 new messages