1

I have an angular service. I am sending a request using $resource to my API. The API is sending a file which is supposed to be downloaded. How do I save it?

NOTE: My API is already sending headers which make the browser download the file.

If I access the API directly from browser, the file downloads. BUT, If I access the API from $resource, nothing happens.

API:

res.writeHead(200, {
    'Content-Type': 'application/octet-stream',
    "content-disposition": "attachment;"
});
res.end(fileText);
Dushyant Bangal
  • 6,048
  • 8
  • 48
  • 80

2 Answers2

1

Try providing a filename, if its a json type otherwise alter content-type accordingly.

"Content-Type": 'application/json'
"content-disposition": "attachment;filename=fname.json"
topless
  • 8,069
  • 11
  • 57
  • 86
  • No, still nothing. It works if accessed directly from browser without giving filename – Dushyant Bangal Apr 13 '16 at 07:29
  • 1
    Can you give a try to [this](http://stackoverflow.com/questions/20904151/download-text-csv-content-as-files-from-server-in-angular) or even better the more elegant and simple answer like [this](http://stackoverflow.com/questions/17836273/export-javascript-data-to-csv-file-without-server-interaction)? – topless Apr 13 '16 at 07:32
  • I am trying a Blob solution, but that doesn't seem a proper way to go. Will give this a try too – Dushyant Bangal Apr 13 '16 at 07:38
1

UPDATE:

I've found a total working solution for this, and unlike the old answer, it works on FF and IE:

var blob = new Blob([response], {type: 'text/json'});

// FOR IE:
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
    window.navigator.msSaveOrOpenBlob(blob);
}

// For Other browsers (tested on Chrome, FF)
else{
    var e = document.createEvent('MouseEvents'),
        a = document.createElement('a');

    a.download = filename;
    a.href = window.URL.createObjectURL(blob);
    a.dataset.downloadurl = ['text/json', a.download, a.href].join(':');
    e.initEvent('click', true, false, window,
      0, 0, 0, 0, 0, false, false, false, false, 0, null);
    a.dispatchEvent(e);
}

Old answer:

Thanks to topless for guiding me to a proper answer. Here's how I got it working:

myService.exportData().$promise.then(function (response) {
    var anchor = angular.element('<a/>');
    anchor.attr({
        href: 'data:attachment/json,' + encodeURI(JSON.stringify(response)),
        target: '_blank',
        download: 'exported logs.log'
    })[0].click();

})

Also, Now I dont need to set the headers at the API side. res.send(myFileText) works just fine!

NOTE: DOES NOT WORK IN IE & SAFARI

Community
  • 1
  • 1
Dushyant Bangal
  • 6,048
  • 8
  • 48
  • 80