download csv file from web api in angular js

前端 未结 10 1635
[愿得一人]
[愿得一人] 2020-11-28 03:23

my API controller is returning a csv file as seen below:

    [HttpPost]
    public HttpResponseMessage GenerateCSV(FieldParameters fieldParams)
    {
                


        
相关标签:
10条回答
  • 2020-11-28 04:20

    I think the best way to download any file generated by REST call is to use window.location example :

        $http({
            url: url,
            method: 'GET'
        })
        .then(function scb(response) {
            var dataResponse = response.data;
            //if response.data for example is : localhost/export/data.csv
            
            //the following will download the file without changing the current page location
            window.location = 'http://'+ response.data
        }, function(response) {
          showWarningNotification($filter('translate')("global.errorGetDataServer"));
        });

    0 讨论(0)
  • 2020-11-28 04:22

    In Angular 1.5, use the $window service to download a file.

    angular.module('app.csv').factory('csvService', csvService);
    
    csvService.$inject = ['$window'];
    
    function csvService($window) {
        function downloadCSV(urlToCSV) {
            $window.location = urlToCSV;
        }
    }
    
    0 讨论(0)
  • 2020-11-28 04:25

    I had to implement this recently. Thought of sharing what I had figured out;

    To make it work in Safari, I had to set target: '_self',. Don't worry about filename in Safari. Looks like it's not supported as mentioned here; https://github.com/konklone/json/issues/56 (http://caniuse.com/#search=download)

    The below code works fine for me in Mozilla, Chrome & Safari;

      var anchor = angular.element('<a/>');
      anchor.css({display: 'none'});
      angular.element(document.body).append(anchor);
      anchor.attr({
        href: 'data:attachment/csv;charset=utf-8,' + encodeURIComponent(data),
        target: '_self',
        download: 'data.csv'
      })[0].click();
      anchor.remove();
    
    0 讨论(0)
  • 2020-11-28 04:26

    The a.download is not supported by IE. At least at the HTML5 "supported" pages. :(

    0 讨论(0)
提交回复
热议问题