简体   繁体   English

从Angular中的服务器下载text / csv内容作为文件

[英]Download text/csv content as files from server in Angular

I am trying to stream a csv file from a node.js server. 我正在尝试从node.js服务器流式传输csv文件。 The server portion is very simple : 服务器部分非常简单:

server.get('/orders' function(req, res) {
  res.setHeader('content-type', 'text/csv');
  res.setHeader('content-disposition', 'attachment; filename='orders.csv');
  return orders.pipe(res); // assuming orders is a csv file readable stream (doesn't have to be a stream, can be a normal response)
}

In my angular controller I am trying to do something like this 在我的角度控制器中,我试图做这样的事情

$scope.csv = function() {
    $http({method: 'GET', url: '/orders'});
};

This function is called when there's a click on a button with ng-click in my view : 在我的视图中ng-click按钮并ng-click时,将调用此函数:

<button ng-click="csv()">.csv</button>

I have looked at other answers about downloading files from server in Angular, but didn't find anything that worked for me. 我已经查看了有关从Angular中的服务器下载文件的其他答案,但没有找到任何对我有用的内容。 Is there a common way to do this ? 有一个共同的方法来做到这一点? Seems like something that should be simple. 似乎应该很简单。

$http service returns a promise which has two callback methods as shown below. $http服务返回一个promise ,它有两个回调方法,如下所示。

$http({method: 'GET', url: '/someUrl'}).
  success(function(data, status, headers, config) {
     var anchor = angular.element('<a/>');
     anchor.attr({
         href: 'data:attachment/csv;charset=utf-8,' + encodeURI(data),
         target: '_blank',
         download: 'filename.csv'
     })[0].click();

  }).
  error(function(data, status, headers, config) {
    // handle error
  });

Most of the references on the web about this issue point out to the fact that you cannot download files via ajax call 'out of the box'. 网上有关此问题的大多数参考文献都指出,您无法通过ajax调用“开箱即用”下载文件。 I have seen (hackish) solutions that involve iframes and also solutions like @dcodesmith's that work and are perfectly viable. 我看过(hackish)解决方案涉及iframes以及像@ dcodesmith这样的解决方案,并且完全可行。

Here's another solution I found that works in Angular and is very straighforward. 这是我发现的另一种解决方案,它在Angular中工作并且非常直观。

In the view , wrap the csv download button with <a> tag the following way : 视图中 ,使用以下方式用<a>标记包装csv下载按钮:

<a target="_self" ng-href="{{csv_link}}">
  <button>download csv</button>
</a>

(Notice the target="_self there, it's crucial to disable Angular's routing inside the ng-app more about it here ) (注意target="_self那里,关键是要更加禁用它角的NG信内部应用程序的路由这里

Inside youre controller you can define csv_link the following way : 在您的控制器内部,您可以通过以下方式定义csv_link

$scope.csv_link = '/orders' + $window.location.search;

(the $window.location.search is optional and onlt if you want to pass additionaly search query to your server) $window.location.search是可选的,如果你想将另外的搜索查询传递给你的服务器,则为onlt)

Now everytime you click the button, it should start downloading. 现在,每次单击该按钮,它都应该开始下载。

var anchor = angular.element('<a/>');
anchor.css({display: 'none'}); // Make sure it's not visible
angular.element(document.body).append(anchor); // Attach to document

anchor.attr({
    href: 'data:attachment/csv;charset=utf-8,' + encodeURI(data),
    target: '_blank',
    download: 'filename.csv'
})[0].click();

anchor.remove(); // Clean it up afterwards

This code works both Mozilla and chrome 此代码适用于Mozilla和chrome

This is what worked for me for IE 11+, Firefox and Chrome. 这对我来说对IE 11 +,Firefox和Chrome都有用。 In safari it downloads a file but as unknown and the filename is not set. 在safari中,它会下载一个文件但是未知,并且未设置文件名。

if (window.navigator.msSaveOrOpenBlob) {
    var blob = new Blob([csvDataString]);  //csv data string as an array.
    // IE hack; see http://msdn.microsoft.com/en-us/library/ie/hh779016.aspx
    window.navigator.msSaveBlob(blob, fileName);
} else {
    var anchor = angular.element('<a/>');
    anchor.css({display: 'none'}); // Make sure it's not visible
    angular.element(document.body).append(anchor); // Attach to document for FireFox

    anchor.attr({
        href: 'data:attachment/csv;charset=utf-8,' + encodeURI(csvDataString),
        target: '_blank',
        download: fileName
})[0].click();
anchor.remove();
}

Using angular 1.5.9 使用角度1.5.9

I made it working like this by setting the window.location to the csv file download url. 我通过将window.location设置为csv文件下载URL使其工作。 Tested and its working with the latest version of Chrome and IE11. 经测试并使用最新版本的Chrome和IE11。

Angular

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

html HTML

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

In php set the below headers for the response: php中为响应设置以下标题:

$headers = [
    'content-type'              => 'text/csv',
    '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',
];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM