2

I am trying to generate a simple text file from a meteor collection. I would like the user to click on a button (let's say 'Convert to text file' button) and he would be able to download a text file containing elements of a given collection converted to text.

I would think that generating a http response on the server side and modying the content type of the http header would do but I don't know how I can achieve that.

Would anybody have suggestions ?

gpasse
  • 4,380
  • 7
  • 44
  • 75
  • possible duplicate of [How to serve a file using iron router or meteor itself?](http://stackoverflow.com/questions/21565991/how-to-serve-a-file-using-iron-router-or-meteor-itself) – David Weldon Oct 22 '14 at 15:34
  • @DavidWeldon correct duplicate – gpasse Oct 22 '14 at 18:34

1 Answers1

4

If using Iron Router, add a route on the server that generates the text file and set the appropriate headers and end the response with the file generated:

Router.map(function() {
  this.route('txtFile', {
    where: 'server',
    path: '/text',
    action: function() {
      var text = "This is the awesome text.";
      var filename = 'textfile' + '.txt';

      var headers = {
        'Content-Type': 'text/plain',
        'Content-Disposition': "attachment; filename=" + filename
      };

      this.response.writeHead(200, headers);
      return this.response.end(text);
    }
  })
});

And on the client:

<a href="/text">Download text</a>
Bjørn Bråthen
  • 410
  • 8
  • 20