版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/shelbyandfxj/article/details/85327313
碰到过几次下载文件(二进制流)时需要带token的需求,现记下来。
下面这种用法应该是用于下载图片的
let token = Cookies.get('token');
let url= "";
let xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); // 设置请求头,必须在open后添加
xhr.setRequestHeader('authorization', token);
xhr.responseType = 'blob'; // 返回类型blob blob 存储着大量的二进制数据
xhr.onload = function () {
if (this.status === 200) {
let blob = this.response;
let reader = new FileReader();
reader.readAsDataURL(blob); // 转换为base64,可以直接放入a标签href
reader.onload = function (e) {
let a = document.createElement('a'); // 转换完成,创建一个a标签用于下载
a.download = name + '.png';
console.log(e)
a.href = e.target.result;
a.click();
};
}
}
xhr.send(); // 发送ajax请求
在用上面的用法来下载文件时,总是下载失败,后面排查发现,a.href后不能用base64的形式,改为:
a.href=window.URL.createObjectURL(blob);
就可以下载了。
后面还有一种方式,不需要使用fileReader。
if (this.status === 200) {
let blob = new Blob([this.response]); // 转成文本存储
let name = xhr.getResponseHeader('content-disposition');
let a = document.createElement('a'); // 转换完成,创建一个a标签用于下载
a.download = name.split('=')[1] + '.zip';
a.href = window.URL.createObjectURL(blob); // 转成本地连接到blob文本
a.click();
}
注意:后台返回的请求头所带的content-type应该是application/octet-stream(二进制流);否则不能下载成功。