我有一个 JSON 对象数组,它是 Nodejs 中函数的结果。我使用 json2xls 将其转换为 Excel 文件,并将其下载到服务器(不在公共(public)文件夹中,并且在 Excel 中格式正确)。
我想向前端发送包含 json 结果的响应(以预览形式显示),并显示一个按钮,他们可以单击该按钮来下载 xlsx 文件或显示 JSON 结果并自动下载文件。
但我无法得到它,而且我已经尝试了很多东西,我快要疯了。 我的 Controller 代码(创建 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);
前端 Controller :
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;
});
};
View :
//display a button to download the export file
<a target="_self" file="{{vm.results}}" download="{{vm.results}}">Download Export File</a>
请有人让我摆脱痛苦。我上过的所有类(class)都没有涵盖这一点。
最佳答案
我终于明白了!由于我一直在寻找让某些东西发挥作用的方法,所以我将分享答案:
在后端:
//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>
关于angularjs - 下载从nodejs传递到前端angularjs的xlsx文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44444406/