Spring - download response as a file
You can't download a file through an XHR request (which is how Angular makes it's requests). See Why threre is no way to download file using ajax request? You either need to go to the URL via $window.open
or do the iframe trick shown here: JavaScript/jQuery to download file via POST with JSON data
I've wrestled with this myself, trying to make it work from the server. Couldn't. Instead...
To clarify on @dnc253's answer,
$window.open(URL)
is a method for having an Angular application open a given URL in another window. (It's really just a testable angular proxy for the universalwindow.open()
.) This is a great solution, preserves your history, and gets the file downloaded and possibly renders it in that fresh browser window if that's supported. But it often runs into popup blockers, which is a huge problem for reliability. Users often simply don't understand what's going on with them. So, if you don't mind immediately downloading the file with the current window, you can simply use the equally effective universal javascript method:location.href = "uriString"
, which works like a charm for me. Angular doesn't even realize anything has happened. I call it in a promise handler for once my POST/PUT operation has completed. If need be, have the POST/PUT return the URL to call, if you can't already infer it. You'll get the same behavior for the user as if it had downloaded in response to the PUT/POST. For example:$http.post(url, payload).then(function(returnData){ var uriString = parseReturn(returnData); location.href="uriString"})
You can, in fact, download something directly from an XHR request, but it requires full support for the HTML5 file API and is usually more trouble than it's worth unless you need to perform local transformations upon the file before you make it available to the user. (Sadly, I lack the time to provide details on that but there are other SO posts about using it.)
It is possible to download a file using XHR request. You can use angular $http to load the file and then use Blob feature of HTML5 to make browser save it. There is a library that can help you with saving: FileSaver.js.