它必须支持 IE、Firefox、Chrome 和 Safari 当前和以前的 3 个版本。 我见过一些使用下载属性的解决方案,该属性仅适用于 Chrome。
我将此数据传递到服务器的原因是这样我可以添加适当的响应 header ,这将强制浏览器显示文件对话框。
我使用 POST 的原因是因为我需要传递一个 JSON 数组,该数组应该以 CSV 字符串的形式返回。
我正在使用 Angular 的 $http.post 服务,该服务返回 CSV 字符串数据,但浏览器未显示保存对话框
Controller code
var downloadUrl ='../csv';
ExportService.postUrl(downloadUrl,
{customerID:$scope.customerID,
startDate:$scope.startDate,
endDate:$scope.endDate
},
$scope.selectedRows).then(function(data) {
return data;
});
ExportService.js has following code.
postUrl: function(url, params, data) {
var deferred = $q.defer();
$http({
url: url,
method: "POST",
params: params,
data: data
}).
success(function(data) {
deferred.resolve(data);
}).error(function() {
deferred.reject("Sorry, Could not fulfill the request at this time");
});
return deferred.promise;
}
以下函数采用 csv 字符串并在 Chrome、Firefox 和 Internet Explorer 中打开文件保存对话框,但在 Safari 中则不然。
function(data){
var charset = "utf-8";
var blob = new Blob([data], {
type: "text/csv;charset="+ charset + ";"
});
if (window.navigator.msSaveOrOpenBlob) {
navigator.msSaveBlob(blob, "Report.csv");
}
else {
var downloadLink = angular.element('<a></a>');
downloadLink.attr('href', window.URL.createObjectURL(blob));
downloadLink.attr('download', "Report.csv");
downloadLink.attr('target', '_blank');
$document.find('body').append(downloadLink);
$timeout(function () {
downloadLink[0].click();
downloadLink.remove();
}, null);
}
}
最佳答案
这是我在 AngularJS 中用来触发下载的方法。
function DownloadFile() {
for (var i = 0; i < arguments.length; i++) {
var iframe = $('<iframe style="visibility: collapse;"></iframe>');
$('body').append(iframe);
var content = iframe[0].contentDocument;
var form = '<form action="' + arguments[i] + '" method="GET"></form>';
content.write(form);
$('form', content).submit();
setTimeout((function (iframe) {
return function () {
iframe.remove();
}
})(iframe), 60000);
}
}
您可以使用任意数量的参数来调用此函数。只需提供一个或多个 URL,此函数就会向您的页面添加一个隐藏的 iframe,并将其保留在那里大约 60 秒。除了收到下载对话框消息之外,用户永远不会注意到。
关于javascript - 在 Angular JS 中使用异步 POST 调用检索 CSV 数据后,如何强制浏览器显示文件下载对话框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30199656/