简体   繁体   中英

Download file button with JS

I need to generate the link and then download the link in one move. I have a button for generation and download and once is clicked i have to call the api to generate the download link for the pdf and then make the browser open the pop up with save item.

            <button type="button" class="btn btn-success btn-block" ng-click="generateAndDownloadPdf()"><i
                class="fa fa-plus"></i>Generate and download invoice</span></button>

and my js controller function looks like :

            $scope.generateAndDownloadPdf = function(){
             //getting download url from api
            api.events.invoice.download($stateParams.eventId, $stateParams.speakerId).then(function(data){
                console.log(data)
                //give url to user

            });

        }

I know that once I have the download url I can use this html code, but was wondering if I can do all in one click for the user.

            <a
           target="_self"
           href="download.url"
           download="file.pdf">
            <button type="button" class="btn btn-success btn-block" ng-click=""><i
                    class="fa fa-plus"></i>Download Invoice</span></button>
        </a>

Thank you all!

you can force the download with this way in yout method "generateAndDownloadPdf",

var anchor = document.createElement('a');
anchor.href = data.downloadUrl;
anchor.target = '_blank';
anchor.download = data.fileName;
anchor.click();

你可以使用

window.location.href= url_to_download;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM