如何通过Meteor下载文件?

时间:2014-07-14 18:28:19

标签: meteor

我正在开发一个系统,用户需要下载由phantomJS生成并保存在服务器上的PDF文件。 这是生成文件并保存到服务器的代码:

var pdf = Meteor.require('phantomjs-pdf');
    var options = {'html': data};

    pdf.convert(options, function(result) {

        /* Using a buffer and callback */
        result.toBuffer(function(returnedBuffer) {});

        /* Using a readable stream */
        var stream = result.toStream();

        /* Using the temp file path */
        var tmpPath = result.getTmpPath();

        /* Using the file writer and callback */
        result.toFile("/tmp/file.pdf", function() {});
    });

看来phantomJS无法下载,我该如何下载该文件?

1 个答案:

答案 0 :(得分:2)

一般解决方案(source code

if (Meteor.isClient) {
  Template.view.events({
    'click button': function () {
      // generate file on server side
      Meteor.call('generateFile', function (error, result) {
          if(error){
              console.error("generateFile error: " ,error);
              return;
          }
          if(result && result.url){
              console.log("File was generated. Trying to download.")
              window.open(result.url);
          }else{
              console.error("Incorrect data returned from 'generateFile' method");
          }
      });
    }
  });
}

if (Meteor.isServer) {
    Future = Npm.require('fibers/future');
    Meteor.methods({
      'generateFile': function (){
           var fut = new Future();
           // async file generation simulated by setTimeout
           setTimeout(function(){
               // here server side should generate pdf, save it to disk and
               // return url to file
               fut["return"]({url:"http://google.com"});
           },2000)
           return fut.wait();
       }
   });
}