如何使用铁路由器或流星本身提供文件? [英] How to serve a file using iron router or meteor itself?

查看:20
本文介绍了如何使用铁路由器或流星本身提供文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的 Meteor 应用程序上提供一个 zip 文件,但我被卡住了.经过大量谷歌搜索后,似乎最好的方法是使用 Iron Router,但我不知道如何:

I'm trying to serve a zip file on my Meteor app but I'm stuck. After a lot of Googling it seems the best way to go is with Iron Router but I don't know how:

Router.map ->
  @route "data",
    where: 'server'
    path: '/data/:id'
    action: ->
      data = getBase64ZipData(this.params.id)
      this.response.writeHead 200, { 'Content-Type': 'application/zip;base64' }
      ???

推荐答案

在服务器上:

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

var fail = function(response) {
  response.statusCode = 404;
  response.end();
};

var dataFile = function() {
  // TODO write a function to translate the id into a file path
  var file = fileFromId(this.params.id);

  // Attempt to read the file size
  var stat = null;
  try {
    stat = fs.statSync(file);
  } catch (_error) {
    return fail(this.response);
  }

  // The hard-coded attachment filename
  var attachmentFilename = 'filename-for-user.zip';

  // Set the headers
  this.response.writeHead(200, {
    'Content-Type': 'application/zip',
    'Content-Disposition': 'attachment; filename=' + attachmentFilename
    'Content-Length': stat.size
  });

  // Pipe the file contents to the response
  fs.createReadStream(file).pipe(this.response);
};

Router.route('/data/:id', dataFile, {where: 'server'});

在客户端:

<a href='/data/123'>download zip</a>

这方面的好处在于它会将文件作为附件下载,并且您可以自定义用户看到的文件名.诀窍是编写 fileFromId 函数.我发现将所有动态生成的文件存储在 /tmp 下是最容易的.

The nice part about this is that it will download the file as an attachment, and you can customize the filename that the user sees. The trick is writing the fileFromId function. I find it's easiest to store all of my dynamically generated files under /tmp.

这个答案假设文件是​​动态生成的.如果你想提供静态内容,你可以把你的文件放在 public 目录下.请参阅这个问题了解更多详情.

This answer assumes that the files are being generated dynamically. If you want to serve static content, you can just put your files under the public directory. See this question for more details.

这篇关于如何使用铁路由器或流星本身提供文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆