mtpultz
mtpultz

Reputation: 18288

Angular solution to downloading dynamically created zip archive

What is the best way to download a dynamically created zip file using AngularJS? I can hit the URL using window.open, but this seems very un-Angular, I could use an iframe, but I don't know how I would get a reference to it in my RestService.

What would be a good Angular implementation to allow for downloading of dynamically created files?

// Current solution
RestService.createInstance( data )

    .then(function( id) {
        //return RestService.generateArchive( id );
        var url = location.href;
        if( url.indexOf('#') != -1 ) { url = url.substring(0, url.indexOf('#')); }
        url += '?ID=' + id;
        window.open( url );
    })

    .then(function( success ) {
        // Obviously won't work due to security
    });

Also, how would you check if the response was rejected? Seems like you can't, but just in case.

Upvotes: 1

Views: 401

Answers (1)

Lander Van Breda
Lander Van Breda

Reputation: 873

Small sample :

Html :

<iframe ng-src="{{url}}" style="display:none"/>

JS:

$scope.url = 'google.com';
RestService.createInstance( data )

    .then(function( id) {
        //return RestService.generateArchive( id );
        var url = location.href;
        if( url.indexOf('#') != -1 ) { url = url.substring(0, url.indexOf('#')); }
        url += '?ID=' + id;
        $scope.url = $sce.trustAsResourceUrl(url);
    })

This should work some remarks :

  • ofcourse don't forget to inject $sce
  • If you download multiple times from the same url, reset the url between downloads to something like google.com

Upvotes: 1

Related Questions