How to serve static content (images, fonts etc.) using iron router

旧街凉风 提交于 2019-11-27 19:20:30

Instead of doing all this, you can just put the files under your public directory. If you add the file:

myApp/public/images/kitten.png

You can access it from your templates like:

<img src="/images/kitten.png">

No routes are needed to make that work.

Beware of overlooking the lead slash.

<img src="images/kitten.png">

the above example will work from your top level routes like /books which makes it easy to miss, but fail on /books/pages.

You probably just need to make sure that the route is in a common area visible on both client and server (This route actually runs on the server) and specify where: 'server'. In addition we need to load the actual file off of disk, which means we need the actual path on the server to the file, and we need to load the 'fs'.

var fs = Npm.require('fs');

Router.map(function() {
  this.route('files', {
    path: '/files/:path(*)',
    where: 'server',
    action: function() {
        var path = this.params.path;
        var basedir = '~/app/';

        console.log('will serve static content @ '+ path);

        var file = fs.readFileSync(basedir + path);

      var headers = {
        'Content-type': 'image/png',
        'Content-Disposition': "attachment; filename=" + path
      };

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

A couple of notes: You should probably move the actual download code into a server only function and call that instead, passing the response in to the function.

You should also do some validation of the path so that you aren't allowing anyone to arbitrarily download files on your server.

In addition, this is setting the content type explicitly, which you will probably want to do for images, but maybe not for other content types. For a generic type you can set it to application/octet-stream

Of course as was mentioned, if your only goal is to have some static content available at deploy time, you should just use the /public directory.

This is a bug in iron-router, which they say is fixed, but I'm still encountering the problem and others have reported on that github issue that it's still a problem.

Edit: It seems to work for files that are directly in /public, but not for files in folders within /public.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!