Download server responded data directly into a file using AngularJs

Sometimes as a AngularJs developer you get some requirements which look easy but they could be tricky, in-short in this post we are having a scenario like:
On a state i do have some dynamic generated links with unique ids, by clicking any of them a ajax request will be fired with it’s id that will fetch some data on success from server (may be json, xml or text etc, in this case we are getting xml data)  after fetching data we have download that data into a .xml file with dynamic name and without creating that file on server at all.

The ideas for solving the current scenario are different, here i am trying to explain it in my way and yes if you could suggest another better one, i am ready to include.

Definitely we need one factory function for http request, one view & one controller.

Starting from factory function: name : DataFactory

getDetailData:function(urToken, baseURL, linkId, generatedId){
    $http.defaults.headers.common["Authorization"] = token;
    return $http.get(baseURL + 'requestId/' + linkId + '/generated/'+ generatedId +'/getDetail');
},

you can easily understand the current code snippet just i have to explain is the return $http.get line. here i have created a http get request with some parameters that matches your server route as well. (from where you are getting data)

now its time to have a controller where we are going to put our core logic to get the scenario done.

$scope.getDataDetail = function (deliverId, index) {
    DataFactory.getDetailData($cookieStore.get('userInfo').token, baseURL, $stateParams.linkId, generatedId)
        .success(function (data, status) {
            var downloadElement = angular.element("a.download");
            downloadElement.attr('href', 'data:application/xml;charset=utf-8,' + data.generatedData);
            downloadElement.get(index).click();
            downloadElement.removeAttr('href');
        }).error(function (error, status) {
            swal("Deliver Data Error", error.errorMessage, "error");
        });
};

line:

downloadElement.attr('href', 'data:application/xml;charset=utf-8,' + data.generatedData);

contains whole logic here:  adding a href attribute with content type

data:application/xml;charset=utf-8

that appends the responded data in link url, after this the next line will click the same link automatically and it will download the file with .xml (this logic is in view part), notice download because we have already created the href link with data in this link, then we have removed the href attribute from this link just after clicking it automatically. (Just remove this line and see what happens :p )

Now time to have a view for user:

<tr ng-if="detailData.length >= 1">
    <td><ul ng-repeat="empData in detailData"><b>{{empData.name}}</b></ul></td>
    <td><ul ng-repeat="empData in detailData">{{empData.deliveredAt | date:'yyyy-MM-dd HH:mm:ss Z'}}</ul>
    </td>
    <td>
        <ul style="cursor:pointer" ng-repeat="ng in detailData">
        <a class="download" id="{{$index}}" ng-click='getDetailData(empData.id, $index);'
           download='{{empData.name}}.xml'>Download File</a>
    </ul>
    </td>
</tr>

here is something that depends on your style, the download='{{empData.name}}.xml’ you can popup a dialog on previous state to get name, or just give a name like as per your choice. Everything is done as per the required scenario.

Hope it solves your problem.

 

Thanks !!

 

Written by 

Joseph Ross is a Principal Consultant at Knoldus Inc. having more than 10 years of experience. Joseph has a passion for identifying challenges and give impactful solutions to the clients. He is a football fan and loves to watch TV series. Joseph has a cross-functional business operations and technology consulting experience. Joseph is familiar with programming languages such as Scala, C++, Java, CSS and HTML.

1 thought on “Download server responded data directly into a file using AngularJs

  1. Hi, Thanks, it worked fine, but small issue i am facing while downloading XSD, the format what i am getting from server is correct (getting it in formatted multiple lines), but once i added it to href tag, format is distracting (appending content in single line) because of this could not use in AEM, could you please suggest how to download same order/format as i ma getting from server ?

    Thanks!

Leave a Reply

%d bloggers like this: