15

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

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

1 回答 1

34

在服务器上:

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.

这个答案假设文件是​​动态生成的。如果要提供静态内容,只需将文件放在public目录下即可。有关更多详细信息,请参阅问题。

于 2014-02-05T00:36:49.370 回答