在Angular中从服务器下载文本/ CSV内容作为文件在Mozilla FireFox中无法正常工作

4

如何在 Angular 中从服务器下载文本/CSV文件

回答者 - 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个回答

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

0

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

$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
  });

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上


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接