/**
* @method
* @param {url} 请求地址?带参数
* @param {fileName} 下载名带后缀
* @returns
* @desc get请求下载
*/
export function getDownload(url, fileName){
let promise = new Promise((resolve, reject)=> {
let httpRequest = new XMLHttpRequest();
httpRequest.open('GET', url, true);
httpRequest.setRequestHeader("Authorization",'Bearer '+ localStorage.getItem('token'));
// httpRequest.setRequestHeader( "Content-Type", "application/json;charset=utf-8");
httpRequest.responseType = "blob";
httpRequest.send();
httpRequest.onload=(res)=>{
if(res.target.status!=200){
this.$message({
message: res.target.status+':'+res.target.statusText,
type: 'error'
});
resolve(false)
}else{
if(res.target.status == 200 && res.target.readyState == 4){
// console.log(httpRequest)
let blob = httpRequest.response;
let reader = new FileReader();
reader.readAsDataURL(blob); // 转换为base64,可以直接放入a属性href
reader.onload = (e)=> {
let link = document.createElement('a');
link.href =e.target.result;
link.download = fileName;
link.click();
link.remove();
resolve(false)
}
}else{
this.$message({
message: error.target.status+':'+error.target.statusText,
type: 'error'
});
resolve(false)
}
}
};
});
return promise;
};
/**
* @method
* @param {url} 访问地址
* @param {param} 参数
* @param {fileName} 下载名带后缀
* @returns
* @desc post请求下载
*/
export function postDownload(url, param, fileName){
let promise = new Promise((resolve, reject)=> {
let httpRequest = new XMLHttpRequest();
httpRequest.open('POST', url, true);
httpRequest.setRequestHeader("Authorization",'Bearer '+ localStorage.getItem('token'));
httpRequest.setRequestHeader( "Content-Type", "application/json;charset=utf-8");
httpRequest.responseType = "blob";
httpRequest.send(JSON.stringify(param));
httpRequest.onload=(res)=>{
if(res.target.status!=200){
this.$message({
message: res.target.status+':'+res.target.statusText,
type: 'error'
});
resolve(false)
}else{
if(res.target.status == 200 && res.target.readyState == 4){
// console.log(httpRequest)
let blob = httpRequest.response;
let reader = new FileReader();
reader.readAsDataURL(blob); // 转换为base64,可以直接放入a属性href
reader.onload = (e)=> {
let link = document.createElement('a');
link.href =e.target.result;
link.download = fileName;
link.click();
link.remove();
resolve(false)
}
}else{
this.$message({
message: error.target.status+':'+error.target.statusText,
type: 'error'
});
resolve(false)
}
}
};
});
return promise;
};
引用方法示例:
//get请求下载
let url = this.serverIp + 'xxxxx' + '?aa=xxx&bb=xxx';
if(this.isDisabled) return;
this.isDisabled=true;
this.postDownload(
url,
'xxxx.xlsx'
).then(
result => this.isDisabled = result,
error => this.isDisabled = false
);
//post请求下载
let json = {
aa:'xxx',
bb:'xxx'
}
if(this.isDisabled) return;
this.isDisabled=true;
this.postDownload(
this.serverIp + 'xxxxx',
json,
'xxxx.xlsx'
).then(
result => this.isDisabled = result,
error => this.isDisabled = false
);
fun(res){
return Promise.resolve(res)
}
this.fun(res).then(res => {
console.log('res',res)
})