这是ajax部分,因为不太了解目前项目里的ajax,所以就自己写了一个
export function downloadWebProtect (params, config = {}) {
return new Promise((resolve, reject) => {
try {
const xhr = new XMLHttpRequest();
xhr.onprogress = config.progress;
xhr.open('GET', `${process.env.PROXY_ENV === 'dev' ? '/api' : ''}/${pkg.name}/download.json?${stringify({...params, ctoken: getCtoken() })}`, true);
xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
xhr.setRequestHeader('Accept', 'application/json');
xhr.responseType = "blob"; //接收二进制流数据
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if (400 >= xhr.status && xhr.status >= 200) {
resolve(xhr.response);
} else {
reject(xhr.responseText)
}
}
}
xhr.onerror = (err) => {
reject(err)
}
xhr.send();
} catch (e) {
console.log(e);
}
})
}
调用ajax的函数:
handleConfirmDownload = () => {
const progress = (event) => {
const {total, loaded} = event;
loaded/total; //当前进度
};
downloadWebProtect({}, { progress }).then((res) => {
const url = window.URL.createObjectURL(res),//将二进制流转为内存地址
a = document.createElement('a');
a.href = url;
a.download = `文件名称.txt`;
document.body.appendChild(a);
a.click();
}).catch((err) => {
console.log('下载失败');
})
}