Download File From Controller in Angular

Screen Shot 2016-05-20 at 11.05.39

Ever had to download a file from your controller in angular? Then you know the struggle is real. You’ll encounter iframe tricks and filesaver.js and all sorts of stuff. But instead of an iframe trick, what you should really do is a link (<a href=”url”></a>) trick!!!

          var a         = document.createElement('a');
          a.href        = yoururl; 
      = '_blank';
    = 'yourfilename.pdf';

Ta da!!! It’ll download your file!!! Note that the file has to exist on your server. You don’t return the file in a post request, you need a url to an existing file instead. So if you’re looking for how to download the answer from a post request, this you can only use this way if you have access to the server and the server writes an actual file to the file system, which can be accessed from the browser.

Leave a Reply

Your email address will not be published.