AngularJS CSV File Download from API

我的梦境 提交于 2021-02-07 21:01:30

问题


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:


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.



来源:https://stackoverflow.com/questions/20259732/angularjs-csv-file-download-from-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!