【问题标题】:Download xlsx file passed from nodejs to frontend angularjs下载从nodejs传递到前端angularjs的xlsx文件
【发布时间】:2017-11-10 16:21:18
【问题描述】:

我有一个 JSON 对象数组,它是 nodejs 中函数的结果。我使用 json2xls 将其转换为 excel 文件,然后下载到服务器(不在公共文件夹中,并且在 Excel 中格式正确)。

我想向前端发送带有 json 结果的响应(以显示为预览)并显示一个按钮,他们可以单击以下载 xlsx 文件或显示 JSON 结果并自动下载文件。

但我无法得到它,而且我已经尝试了很多东西,我快要发疯了。 我的控制器代码(创建 xls 文件的部分):

 var xls = json2xls(results,{});
 var today = (new Date()).toDateString('yyyy-mm-dd');
 var str = today.replace(/\s/g, '');
 var fileName = "RumbleExport_"+ str +".xlsx";
 var file = fs.writeFileSync(fileName,xls,'binary');
 res.download('/home/ubuntu/workspace/'+file);

前端控制器:

vm.exportData = function(day, event, division) {
        console.log('Export registrations button pressed.', vm.export);
      //send the search parameters to the backend to run checks
        $http.post('/api/exportData', vm.export).then(function(response){
            vm.results = response.data;
            console.log("Results",response);
            vm.exportMessage = "Found " + vm.results.length + " registrations.";
        })
        .catch(function(error){
          vm.exportError = error.data;
        });
    };

观点:

//display a button to download the export file
<a target="_self" file="{{vm.results}}" download="{{vm.results}}">Download Export File</a>

请有人让我摆脱痛苦。我上过的所有课程都没有涵盖这个。

【问题讨论】:

    标签: angularjs node.js download


    【解决方案1】:

    我终于明白了!由于我一直在寻找试图让某些东西发挥作用,我将分享答案:

    在后端:

    //save the file to the public/exports folder
    var file = fs.writeFileSync('./public/exports/'+fileName,xls,'binary');
    //send the results to the frontend
    res.json(200).json({results:results, fileName: fileName});
    

    在前端,使用 HTML 下载文件的链接:

    <a href="exports/{{fileName}}" download>Save File</a>
    

    【讨论】:

    • 您安装了这些软件包吗?我必须在页面顶部需要几个包才能使其工作,这意味着它们需要使用 npm 安装
    • 不,我找到了另一种方法
    猜你喜欢
    • 2016-06-12
    • 1970-01-01
    • 2012-11-12
    • 2016-12-29
    • 2019-03-10
    • 2020-07-08
    • 1970-01-01
    • 2019-08-17
    • 2014-11-09
    相关资源
    最近更新 更多