需要加token验证的接口返回文件流下载

2019/04/10 10:10
阅读数 223

没有加token之前,下载文件用的是a标签,直接下载。

 

现在要求是需要在header中加入token。

 1 getDownload(urls, fileName) {
 2             var url = urls;
 3             var xhr = new XMLHttpRequest();
 4             xhr.open("get", url, true);
 5             xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
 6             xhr.setRequestHeader("access-token", store.state.token.token);
 7             xhr.send();
 8             xhr.responseType = "blob"; // 返回类型blob
 9             xhr.onload = function() {
10                 if (this.status === 200) {
11                     let a = document.createElement("a");
12                     let blob = new Blob([this.response], {
13                         type: "text/csv;charset=GBK;"
14                     });
15                     let objectUrl = URL.createObjectURL(blob);
16                     a.setAttribute("href", objectUrl);
17                     a.setAttribute("download", fileName + ".csv");
18                     a.click();
19                 } else {
20                     alert("出现了未知的错误!");
21                 }
22             };
23         },

如图所示,最后解决

原文出处:https://www.cnblogs.com/Zhang-jin/p/12411839.html

展开阅读全文
xhr
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部