如何使用铁路由器或流星本身提供文件?

 多米音乐_34473808 发布于 2023-01-29 12:57

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

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

David Weldon.. 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'});

在客户端:

download zip

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

这个答案假定文件是动态生成的.如果要提供静态内容,可以将文件放在public目录下.有关详细信息,请参阅此问题.

1 个回答
  • 在服务器上:

    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目录下.有关详细信息,请参阅此问题.

    2023-01-29 12:59 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有