我的Grails控制器首先從遠程服務API獲取數據,返回的數據是字符串。然後,我希望將數據作爲csv文件下載到瀏覽器中。我碰到一個類似的職位來到SO偷走了代碼,使用如下的迴應:配置Grails控制器從服務中檢索數據後在瀏覽器中下載文件
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()
但在瀏覽器這不會觸發任何下載窗口。我想知道爲什麼。我用AngularJS做一個POST請求到控制器和解決的承諾如下(JavaScript代碼):
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.";
});