Allow user to download file from public folder Meteor.js

雨燕双飞 提交于 2019-12-08 05:46:00

问题


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.



来源:https://stackoverflow.com/questions/39813313/allow-user-to-download-file-from-public-folder-meteor-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!