簡體   English   中英

使用動態創建的鏈接下載AngularJS中的文件

[英]Use dynamically created link to download file in AngularJS

我正在使用ng-click調用一個函數,該函數向服務器發出一個http請求,然后創建一個鏈接。 如何使用此創建的鏈接來下載附加的文件?

我的范本

<button ng-click="getFile(row)">Download</button>

我的控制器

$scope.getFile = function(row){
    row.isSelected = true;

    var link = null;

    var postData = {
        "data" : {
            "type": "member_report",
            "relationships": {
                "member" : {
                    "data": {
                        "type": "user",
                        "id": memberID
                    }
                }
            }
        }
    }

    ajaxRequest.ajaxPost('http://someApi.com', postData).then(
        function(jsonAPI) {
            link = jsonAPI.links.download; //here is the response link
            //todo something with it to download file   
        },
        function(errorResponse) {           
        }
    );
}

順便說一下,ajaxRequest只是一個簡單的$ http服務包裝器。

如果我了解您,那么我想您想在動態獲取鏈接后立即開始下載,那么您可以按照以下步驟進行操作

$scope.getFile = function(row){
    row.isSelected = true;

    var link = null;

    var postData = {
        "data" : {
            "type": "member_report",
            "relationships": {
                "member" : {
                    "data": {
                        "type": "user",
                        "id": memberID
                    }
                }
            }
        }
    }

    ajaxRequest.ajaxPost('http://someApi.com', postData).then(
        function(jsonAPI) {
            link = jsonAPI.links.download;

            // Now we want to download the link 
           var downloadLink = document.createElement('a');
                downloadLink .href = link;
                // now set the visibility to hidden so that it doesnt effect the frontend layout
                downloadLink .style = 'visibility:hidden';
                downloadLink .download = 'file_name';
                // now append it to the document, generate click and remove the link
                document.body.appendChild(downloadLink );
                downloadLink .click();
                document.body.removeChild(downloadLink );

        },
        function(errorResponse) {           
        }
    );
}

嘗試將鏈接保存在$ scope中。 然后,使用此:

<a target="_self" href={{your variable}} download="foo.pdf">

還要檢查文檔: http : //docs.angularjs.org/guide/

從這里得到的答案:

如何使用AngularJS或Javascript提供文件下載?

我設法使用$ window服務做到了。

ajaxRequest.ajaxPost('http://someApi.com', postData).then(
    function(jsonAPI) {
        link = jsonAPI.links.download;

        $window.location.href = link;

    },
    function(errorResponse) {           
    }
);

只需添加$ window作為依賴項

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM