Angular请求csv文件下载url,并强制下载 [英] Angular Requesting a csv file download url, and force download

查看:847
本文介绍了Angular请求csv文件下载url,并强制下载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



后端是php路由。



我试过解决方案动态添加一个锚标签并追加到它的href属性,csv文件内容后从http请求。但它不为我工作...也因为我们将csc内容附加到href属性,我担心的href的内容允许多少内容的长度。



使用angular 1.5.9的时候,



通过将window.location设置为csv文件下载网址,我可以这样工作。已测试并使用最新版本的Chrome和IE11。



Angular

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

html

 < a target =_ selfng-click =downloadStats()>< i class =fa fa- download>< / i> CSV< / a> 

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

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


How to trigger a csv file download from within Angular on a button click?

The backend is the php route.

I tried solutions which adds an anchor tag dynamically and appends to it's href attribute, the csv file content after getting from the http request. But it didn't work for me... also as we are appending the csc content to the href attribute, i was concerned about the length of the href for how much content it allows.

解决方案

After fiddling with the existing answers, i tried the below and its worked.

Using angular 1.5.9

I made it working like this by setting the window.location to the csv file download url. Tested and its working with the latest version of Chrome and IE11.

Angular

   $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>

In php set the below headers for the response:

$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',
];

这篇关于Angular请求csv文件下载url,并强制下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆