服务器端路由下载文件

时间:2016-03-29 22:19:08

标签: meteor iron-router

我有一个服务器端路由我用来下载文件。这是从客户端按钮单击调用,一切正常。但是,一旦按下按钮一旦它再次无法工作,直到加载另一条路线并返回。我该如何对其进行编码,以便可以多次单击该按钮并且每次都触发服务器端路由?

我的按钮代码看起来像这样......

'click #view_document_download': function (event, tmpl) {
   Router.go('/download_document/' + this._id);
}

我的服务器端路线看起来像这样......

Router.route('/download_document/:_id', function () {

  //Get the file record to download
  var file = files.findOne({_id: this.params._id});

  //Function to take a cfs file and return a base64 string
  var getBase64Data = function(file2, callback) {
    var readStream = file2.createReadStream();
    var buffer = [];
    readStream.on('data', function(chunk) {
      buffer.push(chunk);
    });
    readStream.on('error', function(err) {
      callback(err, null);
    });
    readStream.on('end', function() {
      callback(null, buffer.concat()[0].toString('base64'));
    });
  };

  //Wrap it to make it sync    
  var getBase64DataSync = Meteor.wrapAsync(getBase64Data);

  //Get the base64 string
  var base64str = getBase64DataSync(file);

  //Get the buffer from the string
  var buffer = new Buffer(base64str, 'base64');

  //Create the headers
  var headers = {
    'Content-type': file.original.type,
    'Content-Disposition': 'attachment; filename=' + file.original.name
  };

  this.response.writeHead(200, headers);
  this.response.end(buffer, 'binary');

}, { where: 'server' });

2 个答案:

答案 0 :(得分:0)

也许您应该通过方法从服务器返回一个Object并将其形成客户端的文件?如果可能..

在客户端创建文件非常简单,此时您不必处理路由器。



     function outputFile(filename, data) {
        var blob = new Blob([data], {type: 'text/plain'}); // !note file type..
        if(window.navigator.msSaveOrOpenBlob) {
            window.navigator.msSaveBlob(blob, filename);
        }
        else{
            var elem = window.document.createElement('a');
            elem.href = window.URL.createObjectURL(blob);
            elem.download = filename;        
            document.body.appendChild(elem)
            elem.click();        
            document.body.removeChild(elem);
        }
     }
     
     function getContentAndOutputFile() {
       var content = document.getElementById('content').value;

       outputFile('file.txt', content);
     }

<input id="content" value="test content"/>
<button onClick="getContentAndOutputFile()">Create File</button>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

使用 private void AddButtons_Click(object sender, EventArgs e) { Button btn = new Button(); btn.Click += new EventHandler(StoreTheFirstButton_Click); flowLayoutPanel1.Controls.Add(btn); } private void StoreTheFirstButton_Click(object sender, EventArgs e) { Button button = sender as Button; Button ButtonToSave = button; //ButtonToSave = "First button in flowLayoutPanel1"; }元素代替js'click'事件
第html页

a

服务器中的页面js

<a href="/download_document/{{_id}}" download="true" target="_blank"></a>