Search code examples
angularjshttp-headerswindow.open

$window.open with context / headers


I need to open a window in order to download a file from api endpoint.

currently I am doing this:

let url = this.apiBaseUrl + "/exportToExcel/" + id;
this.$window.open(url, "_blank");

Problem is: the request looses the context (security in header) so that my API Controller blocks the request. How can I get around this issue?


Solution

  • Download the file first, then open it:

    var url = this.apiBaseUrl + "/exportToExcel/" + id;
    var headers = {
       //Put headers here
    };
    var config = { 
       responseType: 'blob',
       headers: headers
    };
    $http.get(url, config).then(function (response) {
        var blob = response.data;
        var u = URL.createObjectURL(blob);
        window.open(u,"_blank");
    });
    

    This will GET the file as a blob, convert it to a object URL, then open it in a new window.