使用Angular获取Excel文档并保存到磁盘

我需要从服务器通过Angulars $ http或其他东西获得一个Excel文件(xlsx)。

问题是REST之类的文件需要自定义头来执行authentication。

如果文件不在auth自定义头文件后面,我可以使用window.open(),这个文件已经过testing并且工作正常,但是文件应该是安全的,所以它被移到了Auth服务之后。

我可以使用angular度从服务器获取响应,并将其作为blob写入文件,但内容是不可读的。

有没有人有一个想法如何实现这一目标?

对任何有兴趣的人

基于George87的答案,我能够find一个基于angular度$http服务,而不是XMLHttpRequest API的解决scheme。 $http的优点是它支持promise。

下面的TypeScript代码应该工作。 只要确保注入$http服务,以及fileSaverService到您的angular度控制器。 config参数可用于设置请求的'Authorization'标头。

 private downloadExcelFile = (url: string, fileName: string) => { const config: angular.IRequestShortcutConfig = { headers: { Authorization: auth, }, responseType: 'blob', }; this.$http.get(`${url}?name=${fileName}`, config) .then((response) => { this.fileSaverService.saveAs(response.data, '<localFileName>.xlsx'); }); } 

我已经find了我的问题的答案,我用XMLHttpRequest。

其他人的示例代码:

 var xhr = new XMLHttpRequest(); xhr.open("GET", "test.xlsx"); xhr.responseType = "blob"; xhr.onload = function () { if (this.status === 200) { xhr.response.type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; saveAs(xhr.response, "test.xlsx") } }; xhr.send(); 

另存为从这里的方法: https : //github.com/eligrey/FileSaver.js