javascripthtmlangularjsdownloadangularjs-ng-click

Download a file while clicking on href link?


is there any way I can download a file when I click on a file using ng-click? Here is what I have now:

<a ng-href="../api/rest/admin/v1/syncsessions/export?fileKey={{syncObject.sourceFiles}}">Download file</a>

This seems to work fine. However, the issue is, when I click on the href, I get redirected to a page with the url on it. As a result, I want to do something like this:

<a ng-click="getExportFiles({{syncObject.sourceFiles}})">Download File</a>

Where getExportFiles is defined as so:

var baseSyncUrl = "../api/rest/admin/{{path.version}}/syncsessions";
var exportSyncFileReq = {method: "GET", url: baseSyncUrl + "/export", params: {fileKey: ""}, path: {version: "v1"}};

$scope.getExportFiles = function(fileKey) {
    var req = exportSyncFileReq;
    req.params.fileKey = fileKey;
    var data = RESTCaller.getConfig(req);
    data.then(function(result) {
        if(result) {
            return result;
        }
    })
}

Contained within result is the link to the file, for example it would be https://<insertURL> since RESTCaller unwraps my promise after calling the exportSynceFileReq API defined. The problem is, when i do ng-click, nothing happens. The file is not downloaded. If I do

<a ng-href="{{getExportFiles(syncObject.sourceFiles)}}">Download File</a>

I get an infinite digest loop. Is there a way where I can simply click on a link, call my API, then download the file automatically without redirecting to another page? Any help would be appreciated. Thanks!


Solution

  • If you have a link from the server you can try to use dummy link and click on it:

    $scope.getExportFiles = function(fileKey) {
        var req = exportSyncFileReq;
        req.params.fileKey = fileKey;
        var data = RESTCaller.getConfig(req);
        data.then(function(result) {
            if (result) {
                var link = document.createElement('a');
                //link.download = 'filename.ext';
                link.href = result;
                link.click();
            }
        })
    }
    

    EDIT: If you're looking for native HTML solution, you can also use the download attribute

    <a href="path" download>Download File</a>
    

    the download attribute also support filename.