1.利用iframe下载
let xhr = new XMLHttpRequest()
xhr.open('GET', url)
xhr.responseType = 'blob'
xhr.setRequestHeader('Authorization', `Bearer ${accessToken}`)
xhr.onreadystatechange = handler
xhr.send()
function handler () {
if (this.readyState === this.DONE) {
if (this.status === 200) {
let iframe = document.createElement('iframe')
iframe.style.display = 'none'
iframe.id = 'g-exportProgram-iframe'
iframe.src = URL.createObjectURL(this.response)
document.body.appendChild(iframe)
} else {
console.error('下载失败')
}
}
}
2.利用a标签下载并且修改文件名
function getBlob(url, cb) {
let xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.responseType = "blob";
xhr.setRequestHeader('Authorization', `Bearer ${accessToken}`)
xhr.onload = function() {
if (xhr.status === 200) {
cb(xhr.response);
}
};
xhr.send();
}
function saveAs(blob, filename) {
//ie10的msSaveBlob 和 msSaveOrOpenBlob 方法允许用户在客户端上保存文件
if (window.navigator.msSaveOrOpenBlob) {
navigator.msSaveBlob(blob, filename);
} else {
let link = document.createElement("a");
let body = document.querySelector("body");
link.href = window.URL.createObjectURL(blob);
link.download = filename;
link.style.display = "none";
body.appendChild(link);
link.click();
body.removeChild(link);
window.URL.revokeObjectURL(link.href);
}
}
function download(url, filename) {
getBlob(url, function(blob) {
saveAs(blob, filename);
});
}
download(url,fileName)