从Angular中的服务器下载text / csv内容,而不是在Mozilla FireFox中工作

时间:2015-08-03 06:31:44

标签: javascript angularjs node.js csv firefox

Download text/csv content as files from server in Angular

回答者 - https://stackoverflow.com/users/2064206/dcodesmith

$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) {
    // if there's an error you should see it here
  });

我实现了这个解决方案,使用angular从服务器下载文件到客户端。这非常在Google Chrome中正常运行。但是这个解决方案无法在Mozilla Firefox中运行

由于

4 个答案:

答案 0 :(得分:9)

您必须先将创建的锚附加到文档中。添加以下内容:

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

Fiddle

答案 1 :(得分:1)

您应该使用encodeURIComponent()代替encodeURI() - 因为#,&amp;,=等字符的编码更好。请参阅https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent

上的文档

答案 2 :(得分:0)

回顾一下,对我有用的解决方案是(使用encodeURIComponent作为maciejlesniak建议):

$http({method: 'GET', url: '/someUrl'}).
success(function(data, status, headers, config) {
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,' + encodeURIComponent(data),
    target: '_blank',
    download: 'filename.csv'
})[0].click();

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

  }).
  error(function(data, status, headers, config) {
    // if there's an error you should see it here
  });

答案 3 :(得分:0)

你也可以解决这个问题。

var anchor = angular.element('<a/>');
anchor.attr({
  href: 'data:attachment/csv;charset=utf-8,' + encodeURI(data),
  target: '_blank',
  download: 'filename.csv'
});
var click = new MouseEvent('click', {
      'view': window,
      'bubbles': true,
      'cancelable': true
  }); 
anchor[0].dispatchEvent(click);

这也应该适用于Firefox,而无需在document.body

上附加锚标记