I am trying to initiate a file download through ajax. I can retrieve the data from the server, but cannot get the browser to open the data. I can't just point the browser's location.href at the endpoint url.
the resource I want to download is being exposed through an endpoint that requires custom http headers, and an authentication bearer token. I cannot change the backend api to allow cookies. Therefore, I cannot just open the url with window.open(url,'_blank')
I can make an ajax request to the endpoint, but I don't know how to download file after I get the response.
$.get( "restAPI/file.pdf", function( data ) {
var w = window.open(null,'_blank')
$(w.document.body).html(data);
});
Does not work either
I was hoping to do something similar to
var w = window.open(data,'_blank')
but that does not work either.
EDIT
The solution, thanks to joyBlanks
$http({method: 'GET',
responseType:'arraybuffer',
headers: {
Accept: 'application/octet-stream',
}, url:url }
).then(function(data) {
var blob = new Blob([data.data]);
if (window.navigator.msSaveBlob)
window.navigator.msSaveBlob(blob, filename);
else {
var link = document.createElement('a');
link.id = filename;
link.href = window.URL.createObjectURL(blob);
link.download = filename;
link.click();
}
});