Thursday, 8 June 2017

Download xlsx file passed from nodejs to frontend angularjs

I have a JSON array of objects that is a result of a function in nodejs. I use json2xls to convert that to an excel file, and it downloads to the server (not in a public folder, and is formatted correctly in Excel).

I would like to send a response to the frontend with the json results (to display as a preview) and show a button they can click to download the xlsx file OR display the JSON results and automatically download the file.

But I can't get it, and I've tried so many things I'm going crazy. My controller code (the part that creates the xls file):

 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);

The frontend 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;
        });
    };

The view:

//display a button to download the export file
<a target="_self" file="" download="">Download Export File</a>

Someone please put me out of my misery. All the classes I've taken and none have covered this.



via user3561890

No comments:

Post a Comment