search

Home  >  Q&A  >  body text

angular.js - AngularJS How to download attachments returned by the server

When using AngularJS $http to send an export data request to the nodejs server, the excel file obtained is garbled, and the console output response.data is as shown below:

The header information returned by the server is as follows:

Accept-Range:bytes
Connection:keep-alive
Content-Disposition:attachment; filename=%E8%A1%A5%E8%B4%B4%E8%B5%84%E6%A0%BC%E5%B7%B2%E5%AE%A1%E6%A0%B8%E4%BF%A1%E6%81%AF%E8%A1%A8.xlsx
Date:Wed, 20 Apr 2016 09:39:33 GMT
Transfer-Encoding:chunked
X-Powered-By:Express

Angular controller:

$scope.export = function() {
    $http({
        url: "/api/exportExcel",
        method: "GET"
    }).then(function(response) {
        var anchor = angular.element('<a/>');
        anchor.attr({
            href: 'data:attachment/xlsx;charset=utf-8,' + encodeURI(response.data),
            target: '_blank',
            download: '2016-04-20.xlsx'
        })[0].click();
    });
}

Angular view:

<button type="button" class="btn" ng-click="export()">导出</button>

How to get the correct and available excel file? What is the common implementation method for exporting data to excel like this? grateful!

伊谢尔伦伊谢尔伦2811 days ago566

reply all(1)I'll reply

  • 滿天的星座

    滿天的星座2017-05-15 17:03:06

    Try using $window.location = '/api/exportExcel' directly?

    reply
    0
  • Cancelreply