2012-10-31 39 views
2

我所做的服务端返回csv格式时,我打电话跟$ HTTP GET与角度的服务,如果用户点击按钮..angularjs CSV下载到本地

So the return is like 1,2,3,4,5,6,7,8,9,10 

什么是给最好的办法用户的方式来保存它们的本地机器?

+1

,如果你的服务器已经创建的格式是可以接受您的用户数据,可以在按钮即可将其转发到该网址(确保mime类型是正确的,当然!) –

+2

您最好将下载推送给使用服务器的用户。你有什么样的服务器体系结构(例如PHP或Java或Node) –

+0

但棘手的问题是服务只能接受POST。如果服务可以接受GET,那么重定向用户是没有问题的。但是我怎样才能用POST做? – MomentH

回答

6

有两个选项

1)从您的服务器发送csv。

2)数据URI。我想这是你要求的。下面是一个例子

/** 
* @param{string} content The contents of a file to download. 
* @param{string} fileName The name to save the file as on the user's computer. 
*/ 
function(content, fileName) { 
    var dataUrl = 'data:text/csv;utf-9,' + encodeURI(content); 
    var link = document.createElement('a'); 
    angular.element(link) 
    .attr('href', dataUrl) 
    .attr('download', fileName) // Pretty much only works in chrome 
    link.click(); 
} 
+0

嘿嘿。 UTF-9。 http://en.wikipedia.org/wiki/UTF-9_and_UTF-18 –

0

你可以试试Alasql库,它可以在CSV格式保存数据的一行:

function myCtrl($scope) { 
    $scope.filename = "mydata.csv"; 
    $scope.cities = [{city:"Odessa",population:100000}, 
        {city:"Voronezh",population:201022}, 
        {city: "Paris", population: 3000000}]; 

    $scope.saveCSV = function(filename, content) { 
      alasql('SELECT city, population INTO CSV("'+$scope.filename+'",{headers:true}) FROM ?', 
      [$scope.cities]); 
    }; 
}; 

the full example code中的jsfiddle。

在这个例子中,Alasql使用SELECT操作符从数据数组中选择需要的字段(AngularJS创建$$ hashKey字段,这可能不需要用户)。如果你没有这些数据,使用 简单地导出为CSV与档案:

alasql('SELECT * INTO CSV('mydata.csv') FROM ?',[$scope.data]);