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);
2
  • What request type is it? If it's GET, try to use download attribute to a link. Commented Apr 13, 2016 at 7:28
  • GET, POST neither worked. Download attribute? Commented Apr 13, 2016 at 7:52

2 Answers 2

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"
Sign up to request clarification or add additional context in comments.

3 Comments

No, still nothing. It works if accessed directly from browser without giving filename
Can you give a try to this or even better the more elegant and simple answer like this?
I am trying a Blob solution, but that doesn't seem a proper way to go. Will give this a try too
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

1 Comment

The only problem is that it will not work in IE and Safari.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.