const getHeaders = () => {
return {
XXX_TOKEN1: 'xxx',
XXX_TOKEN2: 'xxx',
};
};
function downloadWithHeaders(url: string, method: string = 'GET', cb: { (blobUrl: string): void }) {
const xhr = new XMLHttpRequest();
xhr.open(method, url, true);
const headers = getHeaders();
for (const [k, v] of Object.entries(headers)) {
xhr.setRequestHeader(k, v);
}
xhr.responseType = 'blob';
xhr.onload = function onload() {
if (this.status === 200) {
const blob = this.response;
const blobUrl = window.URL.createObjectURL(blob);
cb(blobUrl);
} else {
console.error(`【下载报错】method:${method}, url:${url}, headers:${headers}`);
}
};
xhr.send();
}
export function downloadExcelWithHeaders(
url: string,
method: string = 'GET',
fileName: string = '文件.xlsx',
) {
const cb = (blobUrl: string) => {
const a = document.createElement('a');
a.download = fileName;
a.href = blobUrl;
a.click();
window.URL.revokeObjectURL(blobUrl);
};
downloadWithHeaders(url, method, cb);
}
export function downloadImageWithHeaders(url: string, method: string = 'GET', el: HTMLElement) {
const cb = (blobUrl: string) => {
const img = document.createElement('img');
img.style.width = '100%';
img.style.height = '100%';
img.src = blobUrl;
el.appendChild(img);
window.URL.revokeObjectURL(blobUrl);
};
downloadWithHeaders(url, method, cb);
}