1. post 請求
export default function (data) {
axios({
method: 'post',
url: data.url, //後端接口地址
responseType: 'blob', //bolb格式的請求方式
headers: {
Authentication: getToken('Admin-Token') //請求頭
},
data: data.data //需要傳給後端的請求參數體
}).then(res => {
const BLOB = res.data;
const fileReader = new FileReader();
fileReader.readAsDataURL(BLOB); //對請求返回的文件進行處理
fileReader.onload = (e) => {
let a = document.createElement('a');
a.download = data.name + '.xlsx'
a.href = e.target.result;
document.body.appendChild(a)
a.click();
document.body.removeChild(a)
}
}).catch(err => {
console.log(err.message)
})
}
2. get 請求
export default function (data) {
axios({
url: data.url,
method: 'get',
responseType: 'blob',
params: data.data, //與post傳參方式不同之處
headers: {
Authentication: getToken()
}
}).then(res => {
var blob = new Blob([res.data],
{type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=utf-8'});
var filename = data.name + '.xlsx';
var downloadElement = document.createElement('a');
var href = window.URL.createObjectURL(blob); //創建下載的鏈接
downloadElement.style.display = 'none';
downloadElement.href = href;
downloadElement.download =filename ; //下載後文件名
document.body.appendChild(downloadElement);
downloadElement.click(); //點擊下載
document.body.removeChild(downloadElement); //下載完成移除元素
window.URL.revokeObjectURL(href); //釋放掉blob對象
}
}
參考文章:https://www.cnblogs.com/zz-zrr/p/11970935.html