3

I have an admin control panel where admin users can set a few options and then click a button to run a report. The report should return a CSV file download prompt to the user.

I am using ui-router and $resource services. The response headers/mime type are set correctly, but the CSV file is returned as text (no file download initiated) by the $resource handler.

I tried creating the download link directly, by forming a querystring from the $scope, but unfortunately my API's authentication scheme uses a custom HTTP header token and it's not possible to send that to the API (which is also on another subdomain) via an anchor tag, such as this one:

<a href="http://example.com/admin/report/csv?usertype=1&days=5">Run</a>

Is there a way to initiate a file download prompt using an XHR request (with custom header)?

1 Answer 1

4

I'm using a custom header token so downloading the report via a simple link is impossible; the request has to be made via XHR. My two-part solution:

  1. Returned the CSV data from the API directly as text, removing file attachment headers. This is the correct solution, anyway, because it keeps the REST JSON API unconcerned with file downloads, which are a browser concept.

  2. Wrapped the API response data in a Blob, and then used https://github.com/eligrey/FileSaver.js to initiate a file download.

A drawback is this requires IE10+, but that is okay in my case.

Sign up to request clarification or add additional context in comments.

2 Comments

that seems reasonable, but do you have a fiddle or gist as an example? or can you update the answer with a script? thanks
Thanks Harper for your response. PM, please find below a bit of code following Harper post that works like a charm! in view: <a ng-click="exportToCsv()"> in controller, assuming the rest service returns an object with member called data which contains the csv raw data: $scope.exportToCsv = function () { ReportAction.runFullReport($scope.filterCriteria).$promise.then(function (result) { var blob = new Blob([result.data], { type: "text/plain;charset=utf-8" }); saveAs(blob, "report.csv"); }), function() { console.log('error'); }; };

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.