XMLHttpRequest
跨域请求CORS
会出现http响应头不全的情况,但是在chrome中正常显示,js获取不全。
需要在服务端增加配置响应的请求头。response.setHeader("Access-Control-Expose-Headers","Content-Disposition");
即可拿到响应头
async downloadFile ( url :string ,fileName?:string ){
const req = new XMLHttpRequest();
const token = 'get token'
req.open('get', url);
req.setRequestHeader('token', token);
req.responseType = 'blob';
req.onreadystatechange = ()=>{
if (req.readyState === 4 && req.status === 200) {
const headerfileName = req.getResponseHeader('Content-Disposition') ;
if(headerfileName){
fileName = decodeURI(headerfileName.replace('attachment;filename=', ''));
}
const blob = new Blob([req.response]);
const blobUrl = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = blobUrl;
a.download = fileName ;
a.click();
}else{
console.log('服务异常。');
}
}
req.send();
}