Referencing How to implement file download with iron router or meteor itself?
HTML:
<template name="example">
<a href="{{pathFor 'csv'}}">Click here to download CSV</a>
</template>
JS:
// Sample collection
var SampleData = new Mongo.Collection("sampleData");
// generate some example data
if (Meteor.isServer) {
Meteor.startup(function() {
var sampleDataCursor = SampleData.find();
if (sampleDataCursor.count() === 0) {
for(var i=1; i<=50; i++) {
SampleData.insert({Name: "Name" + i, Address: "Address" + i, Description:"Description" + i});
}
}
});
}
Router.route('/csv', {
where: 'server',
action: function () {
var filename = 'meteor_sampledata.csv';
var fileData = "";
var headers = {
'Content-type': 'text/csv',
'Content-Disposition': "attachment; filename=" + filename
};
var records = SampleData.find();
// create a CSV string. Keep in mind you may need to handle quotes and commas.
records.forEach(function(rec) {
fileData += rec.Name + "," + rec.Address + "," + rec.Description + "\r\n";
});
this.response.writeHead(200, headers);
return this.response.end(fileData);
}
});