从Angular中的服务器下载文本/ csv内容,而不是在Mozilla FireFox中工作
从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 });
我实现了这个解决scheme,使用angular度从服务器下载文件到客户端。 这在Google Chrome中运行良好 。 但是这个解决scheme在Mozilla Firefox中不起作用 。
谢谢
您必须先将创build的锚点附加到文档中。 添加以下内容:
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
小提琴
你应该使用encodeURIComponent()
而不是encodeURI()
– 因为像#,&,=这样的字符编码效果更好。 请参阅https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent上的文档
简单来说,我的解决scheme是(使用encodeURIComponent maciejlesniakbuild议):
$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 });
你也可以解决这个问题。
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锚定标签