Download a file with AngularJS

后端 未结 2 805
小鲜肉
小鲜肉 2020-12-10 19:41

I need to provide a link to download a file, the link must be hidden and accessible by any users, Here is my code , there are no errors whatsoever, but I can\'t even get the

2条回答
  •  鱼传尺愫
    2020-12-10 20:18

    I had to achieve the functionality. Also had to make sure that it works for all the major supported browsers. Here's the solution for the same!!!

    Happy Coding!!!

    Your View/HTML

     Download 
    

    Your Controller

    $scope.downloadInvoice = function () {
        $http.post(url,requestData, {responseType:'arraybuffer',headers:header
            })
                .success(function (response) {
                    var file = new Blob([response], {type: 'application/pdf'});
    
                    var isChrome = !!window.chrome && !!window.chrome.webstore;
                    var isIE = /*@cc_on!@*/false || !!document.documentMode;
                    var isEdge = !isIE && !!window.StyleMedia;
    
    
                    if (isChrome){
                        var url = window.URL || window.webkitURL;
    
                        var downloadLink = angular.element('');
                        downloadLink.attr('href',url.createObjectURL(file));
                        downloadLink.attr('target','_self');
                        downloadLink.attr('download', 'invoice.pdf');
                        downloadLink[0].click();
                    }
                    else if(isEdge || isIE){
                        window.navigator.msSaveOrOpenBlob(file,'invoice.pdf');
    
                    }
                    else {
                        var fileURL = URL.createObjectURL(file);
                        window.open(fileURL);
                    }
    
                })
    };
    

提交回复
热议问题