获取文件流
downloadFile() {
const that = this
const ajax = new XMLHttpRequest()
ajax.responseType = 'blob'
const url: string = 'urlstr';
ajax.open("GET",url,true)
ajax.setRequestHeader('Authorization','Bearer ' + localStorage.getItem('token'))
ajax.onreadystatechange = function(){
if(this.readyState == 4) {
if(this.status == 200) {
if(this.response.type == "application/octet-stream"){
const fileType: string = "application/octet-stream";
const fileName: string = 'fileName.cpt';
that.downloadHandler(this.response, fileName, fileType);
}else{
}
}
}else if (this.readyState == 2) {
if(this.status == 200) {
this.responseType = "blob"
} else {
this.responseType = "text"
}
}
}
ajax.send(null);
}
保存文件
downloadHandler(data, fileName, type) {
let blob = new Blob([data], {type:type||"application/octet-stream"});
let downloadElement = document.createElement('a');
let href = window.URL.createObjectURL(blob);
downloadElement.href = href;
downloadElement.download = fileName;
document.body.appendChild(downloadElement);
downloadElement.click();
document.body.removeChild(downloadElement);
window.URL.revokeObjectURL(href);
}