简体   繁体   中英

How to forward AngularJS $http response to the browser?

I have a backend with header-based authentication and I want to download a file from it. With cookie-based authentication it is simple: you render a link to a file into <a href...> and let browser to handle the rest.

I have this code:

    $http.get(url).then(function (response) {
      // do something
    }, function (response) {
      alert("ERROR");
    });

I have injection of HTTP headers, so in this case $http.get will populate them for us. What I want to do is to feed this response to $window , so from user perspective it will looks like usual file download.

Is there any way of doing this? Any other options are welcomed.

I assume what you want is to push the file to the client without them needing to click anything else on the page. You can cause this to occur without needing to mess with $window at all.

Here is an example of how I pushed a zip file created in the browser that contained multiple selected regions of a canvas:

var downloader = angular.element('<a>download</a>');
downloader.attr('href', "data:application/zip;base64," + content);
downloader.attr('download', 'my.zip')

var ev = $document[0].createEvent("MouseEvent");
ev.initMouseEvent(
    "click",
    true /* bubble */, true /* cancelable */,
    window, null,
    0, 0, 0, 0, /* coordinates */
    false, false, false, false, /* modifier keys */
    0 /*left*/, null
);
downloader[0].dispatchEvent(ev);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM