方法一
const token= window.sessionStorage.getItem('access_token');//如果有
function downLoadByUrl(url){
var xhr = new XMLHttpRequest();
//GET请求,请求路径url,async(是否异步)
xhr.open('GET', url, true);
//设置请求头参数的方式,如果没有可忽略此行代码
xhr.setRequestHeader("authorization", token);
//设置响应类型为 blob
xhr.responseType = 'blob';
//关键部分
xhr.onload = function (e) {
//如果请求执行成功
if (this.status == 200) {
var blob = this.response;
var filename = "我是文件名";//如123.xls
var a = document.createElement('a');
blob.type = "application/octet-stream";
//创键临时url对象
var url = URL.createObjectURL(blob);
a.href = url;
a.download=filename;
a.click();
//释放之前创建的URL对象
window.URL.revokeObjectURL(url);
}
};
//发送请求
xhr.send();
}
方法二
url是请求接口地址
handleDownLoad(url);
function handleDownLoad(url) {
fetch(url, {
method: 'GET',
headers: new Headers({
'authorization': window.sessionStorage.getItem('access_token')
}),
})
.then(res => res.blob())
.then(data => {
const blobUrl = window.URL.createObjectURL(data);
download(blobUrl);
});
}
//模拟a标签实现下载excel文件
function download(blobUrl) {
const a = document.createElement('a');
a.download = new Date().getTime().toString() + '.xlsx';
a.href = blobUrl;
a.click();
}
在这里我需要带参数查询并下载文件
$('.export-btn').on('click', function () {
var name = $(".searchVouchername").val();
var voucherNo = $(".searchVoucherNo").val();
var status = $(".searchStatus option:selected").val();
var created_time = $(".searchCreatedTime").val();
var arr = created_time.split('~');
var createdstarttime = arr[0] && arr[0].trim();
var createdendtime = arr[1] && arr[1].trim();
var username = $(".searchUsername").val();
var receivetime = $(".searchReceiveTime").val();
arr = receivetime.split('~');
var receivestarttime = arr[0] && arr[0].trim();
var receiveendtime = arr[1] && arr[1].trim();
var pinurl = '?name=' + name + '&voucherNo=' + voucherNo + '&status=' + status + '&createdstarttime=' + createdstarttime + '&createdendtime=' + createdendtime + '&username=' + username
+ '&receivestarttime=' + receivestarttime + '&receiveendtime=' + receiveendtime
var url = baseurl+ '/admin/voucher/export' + pinurl;
handleDownLoad(url);
});