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

查看:23
本文介绍了从 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 数据,删除文件 attachment 标头.无论如何,这是正确的解决方案,因为它使 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天全站免登陆