在使用Angular JS中的异步POST调用检索CSV数据后,如何强制浏览器显示文件下载对话框?

时间:2022-12-03 20:21:16

It must support IE,Firefox, Chrome and Safari current and previous 3 versions. I have seen some solutions using download attribute which works in Chrome only.

它必须支持IE,Firefox,Chrome和Safari当前和之前的3个版本。我见过一些使用download属性的解决方案,仅适用于Chrome。

The reason I am passing this data to server is so that I can add appropriate response headers which would force the browser to present a file dialog box.

我将此数据传递给服务器的原因是我可以添加适当的响应标头,这将强制浏览器显示文件对话框。

The reason I am using a POST is because I need to pass a JSON array which should come back as CSV string.

我使用POST的原因是因为我需要传递一个JSON数组,该数组应该以CSV字符串形式返回。

I am using angular's $http.post service which is giving back the CSV string data but browser is not presenting a save dialog

我正在使用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;
    }

following function takes a csv string and opens a file save dialog in Chrome, Firefox and Internet explorer but not in Safari.

以下函数接受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);
        }

}

1 个解决方案

#1


This is what I use to trigger a download in AngularJS.

这是我用来触发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);
                }
}

You can call this function with as many arguments as you'd like. Just supply one or more URLs, and this function will add a hidden iframe to your page, and keep it there for about sixty seconds. The user will never notice, besides the fact that he gets a download dialog message.

您可以使用任意数量的参数调用此函数。只需提供一个或多个网址,此功能会向您的网页添加隐藏的iframe,并将其保留约60秒。除了获得下载对话框消息之外,用户将永远不会注意到。

#1


This is what I use to trigger a download in AngularJS.

这是我用来触发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);
                }
}

You can call this function with as many arguments as you'd like. Just supply one or more URLs, and this function will add a hidden iframe to your page, and keep it there for about sixty seconds. The user will never notice, besides the fact that he gets a download dialog message.

您可以使用任意数量的参数调用此函数。只需提供一个或多个网址,此功能会向您的网页添加隐藏的iframe,并将其保留约60秒。除了获得下载对话框消息之外,用户将永远不会注意到。