Angular请求csv文件下载URL,并强制下载

时间:2017-01-23 18:03:24

标签: javascript angularjs csv download

如何在单击按钮时从Angular中触发csv文件下载?

后端是php路由。

我尝试了动态添加锚标记的解决方案,并附加到它的href属性,从http请求获取后的csv文件内容。但它对我不起作用...同样,当我们将csc内容附加到href属性时,我担心href的长度允许它包含多少内容。

1 个答案:

答案 0 :(得分:0)

在摆弄现有答案后,我尝试了下面的工作。

使用angular 1.5.9

我通过将window.location设置为csv文件下载URL使其工作。测试并使用最新版本的Chrome和IE11。

   $scope.downloadStats = function downloadStats{
        var csvFileRoute = '/stats/download';
        $window.location = url;
    }

HTML

<a target="_self" ng-click="downloadStats()"><i class="fa fa-download"></i> CSV</a>

在php中为响应设置以下标题:

$headers = [
    'content-type'              => 'text/cvs',
    'Content-Disposition'       => 'attachment; filename="export.csv"',
    'Cache-control'             => 'private, must-revalidate, post-check=0, pre-check=0',
    'Content-transfer-encoding' => 'binary',
    'Expires' => '0',
    'Pragma' => 'public',
];