我有一个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>
有人请把我从痛苦中解救出来。我所参加的所有课程都没有涵盖这一点。
答案 0 :(得分: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>