Allow user to download file from public folder Met

2019-06-03 17:34发布

问题:

I am generating a .xlsx file and then place it into "../web.browser/app/cheques.xlsx". As I understand it is an equivalent of public folder inside the build. The problem is that I can't manage to make it available for download.

This is a fragment of code in server method, where I place a file into that place:

workbook.xlsx.writeFile("../web.browser/app/cheques.xlsx")
  .then(function() {
    console.log('done');
  });

So should I use fs or Picker.route to do the job?

回答1:

It's not advisable to do this. In production the build directory won't be available to you anyway.

You have a few choices:

  1. Store the files in a defined place in the file system (not /public) that something else like Apache can serve from
  2. Store the files in an Amazon S3 bucket, and then let AWS serve them
  3. Store the files in a Mongo collection, uing a package like this https://github.com/vsivsi/meteor-file-collection

I prefer the last one, as all your data and files are in one place.



回答2:

Here is the solution which made me very happy. Thanks to my friend's proposition, I placed .xlsx generating code inside a server-side route:


Excel = require('exceljs');
fs = require('fs');

Picker.route('/export/:_cheques', function(params, req, res, next) {
    let data = Cheques.find(query).map((it) => {
      return {
        cheque_number: it.cheque_number, // & other data
      }
    });

    let workbook = new Excel.Workbook();

    let sheet = workbook.addWorksheet('Cheques', { properties: { tabColor: { argb: 'FFC0000' } } });

    sheet.columns = [
      { header: 'Номер чека', key: 'cheque_number', width: 30 },  // & other columns
    ];


    data.map(function(it) {
      sheet.addRow({
        cheque_number: it.cheque_number,  // & other data
      })
    });

    res.writeHead(200, {
      'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      'Content-Disposition': headerFilename,
    });

    workbook.xlsx.write(res)
)};

Then I just added a link inside my html:


<a href='/export/all' rel='external' download> Export my file </a>

...and it works perfect. "Like a charm", as you guys like to say : )

I hope this will help somebody.