使用angularjs中的restapi在postman中下载文本文件但不在浏览器中下载

时间:2018-04-04 10:47:21

标签: angularjs angularjs-ng-href

$scope.newFile是我对后端的回复。实际上我的回复应该是一个文本文件,它在postman中工作。但是在浏览器中,我得到了

  

无法获得   /Organizer/%7B%22data%22:%22id/tname/temail/tphone/twebsite/tvenue/ttags/n83/tAny%20Name/ta@b.com/t9009009009/thttp://www.anyname.com/tHall %20A / ttag1,%20tag2,%20tag3 / nsunitha / tsunitha @ gmail.com / t55555541 / thttp://www.sunitha.com/nSuhasini/tsuha@gmail.com/t955555544/thttp://www.suha.com /nRaichel/traichel@gmail.com/t955548458/thttp://www.raichel.com/n%22,%22status%22:200,%22config%22:%7B%22method%22:%22GET%22,% 22transformRequest%22:[空],%22transformResponse%22:[空],%22jsonpCallbackParam%22:%22callback%22%22headers%22:%7B%22Authorization%22:%22Token%2013946cc6c575d61b042b01b6905f1d239b3d9b08%22%22Accept%22 :%22application / JSON,%20text /纯,%20 * / *%22%7D,%22url%22:%22http:// http://localhost/1290//entity/campaigns/download_exhibitors/%22%7D,%22statusText%22:%22OK%22,%22xhrStatus%22:%22complete%22%7D

Service.js

var url =' http://localhost/1290/';

function downloadExhibitor() {

        var token = 129821sahh;
        var auth = "Token" + ' ' + token;

        var config = {
            headers: {
                'Content-Type': 'text/plain',
                'Authorization': auth
            }
        }

        return $http.get(url + 'entity/campaigns/download_exhibitors/', config)
               .then(successHandler, errorHandler);
}

function successHandler(response){
    /* we've got file's data from server */
    return response.data;
}

function errorHandler(error){
    /* we've got error response from server */
    throw new Error('ERROR ' + error);
}

并最终进行服务调用

JS:

$scope.newFile = "";
service.downloadExhibitor()
       .then(function(data){
                $scope.newFile = data;
             }, function(error){ 
                console.log(error);
             });

HTML:

    <button class="btn" ng-click="downloadAllExhibitors();">
<a ng-href="{{newFile}}" target="_blank">Download</a></button>

2 个答案:

答案 0 :(得分:2)

您可以在控制器中尝试以下代码...

XLSXwriter

答案 1 :(得分:0)

在控制器中使用以下代码使我的工作变得简单,并最终下载了该文件。

            var file = new Blob([data], {
                    type: 'text/plain'
                });
                if (navigator.userAgent.indexOf('MSIE') !== -1 ||
                    navigator.appVersion.indexOf('Trident/') > 0) {
                    window.navigator.msSaveOrOpenBlob(file);
                } else {
                    var a = window.document.createElement("a");
                    a.href = window.URL.createObjectURL(file, {
                        type: "text/plain"
                    });
                    a.download = "filename.csv";
                    document.body.appendChild(a);
                    a.click(); 
                    document.body.removeChild(a);
                }