从API下载AngularJS CSV文件 [英] AngularJS CSV File Download from API

查看:46
本文介绍了从API下载AngularJS CSV文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个管理员控制面板,管理员用户可以在其中设置一些选项,然后单击一个按钮来运行报告.该报告应向用户返回CSV文件下载提示.

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.

我正在使用 ui-router $ resource 服务.响应头/MIME类型设置正确,但是 $ resource 处理程序将CSV文件作为文本返回(未启动文件下载).

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.

我尝试通过从 $ scope 形成查询字符串来直接创建下载链接,但是很遗憾,我的API的身份验证方案使用了自定义HTTP标头令牌,因此无法将其发送到API(也位于另一个子域上),例如锚定标签:

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>

是否可以使用XHR请求(带有自定义标头)来启动文件下载提示?

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

推荐答案

我使用的是自定义标头令牌,因此无法通过简单的链接下载报告;该请求必须通过 XHR 进行.我的两部分解决方案:

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. 直接从API作为文本返回了CSV数据,删除了文件附件标头.无论如何,这是正确的解决方案,因为它使REST JSON API与文件下载无关,这是浏览器的概念.

  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.

将API响应数据包装在 Blob 中,然后使用https://github.com/eligrey/FileSaver.js 来启动文件下载.

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

一个缺点是这需要IE10 +,但就我而言是可以的.

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

这篇关于从API下载AngularJS CSV文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆