Configure the Grails controller to download the file to the browser after retrieving the service data

advertisements

My controller in Grails first fetches the data from a remote service API, and the returned data is a String. Then I would like to have the data downloaded as a csv file in the browser. I came across a similar post on SO and stole the code for using the response as below:

String exportResults = dataService.getDataFromService()
response.setHeader "Content-disposition", "attachment; filename=data_export.csv"
response.contentType = 'text/csv'
response.outputStream << exportResults.getBytes() //getBytes() not portable
response.outputStream.flush()

But this does not trigger any download window in the browser. I was wondering why. I use AngularJS to make a POST request to the controller and resolve the promise as below (JavaScript code):

ExportService.exportData(some_params).then(function(data) {
               $log.info('export promise resolved: ');
               //window.open(data, '_blank', ''); //not working
               }).catch(function(err) {
               $scope.message = "failed to retrieve data from export service";
               $log.error(err);
               }).finally(function(complete) {
                 $scope.message = "Data export completed.";
               });


You need to replace 'text/csv' with 'application/octet-stream' for response.contentType. The content type 'application/octet-stream' is used for a binary file.