Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
162 views
in Technique[技术] by (71.8m points)

How to serve a file using iron router or meteor itself?

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' }
      ???
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

On the server:

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

On the client:

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

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...