Kristoffer K
Kristoffer K

Reputation: 2053

How to handle conditional file downloads in meteor.js

In php you can use headers to force downloads of files, and also to hide actual file locations etc.

This is useful if you only want certain users under certain conditions to be able to download certain files.

How would I do this in meteor? I've played around with the Node.js fs module, and managed to retrieve a binary version of the file on the client. But how would I turn this to an actual file that's downloaded?

Thanks!

Upvotes: 4

Views: 1427

Answers (1)

Micha Roon
Micha Roon

Reputation: 4009

Three easy steps:

  1. use meteorite
  2. add the iron-router package: mrt add iron-router
  3. create a server method to serve your file. Here is how an exemple:

    Router.map(function () {
      this.route('get-image', {
         where: 'server',
         path: '/img',
         action: function () {
            console.log('retrieving ' + this.request.query.name);
            this.response.writeHead(200, {'Content-type': 'image/png'}, this.request.query.name);
            this.response.end(fs.readFileSync(uploadPath + this.request.query.name));
        }
      });
    });
    

In this example the request is a HTTP GET with one parameter name=name-of-pdf.pdf.

That's really all. Hope it was what you were looking for.

Upvotes: 7

Related Questions