1.直接引入axios
import axios from 'axios'; // 引入axios
axios.defaults.headers.token = JSON.parse(localStorage.getItem('XXXX')).token //没有token可删除
axios({
methods: 'get',
url: 'XXXX',
responseType: 'blob'
})
.then((res) =>{
const content = res
const blob = new Blob([content.data])
const fileName = '活动数据.xlsx'
const elink = document.createElement('a')
elink.download = fileName
elink.style.display = 'none'
elink.href = URL.createObjectURL(blob)
document.body.appendChild(elink)
elink.click()
URL.revokeObjectURL(elink.href) // 释放URL 对象
document.body.removeChild(elink)
})
2.封装方法
http.js (我自己的get请求,post自己改)
import axios from 'axios'; // 引入axios
export let pathUrl = 'XXXXXXXXXXXXXXx';
const instance = axios.create({
baseURL: pathUrl,
timeout: 50000,
headers: {
'Content-Type': 'application/json'
},
})
export function httpGetBlob(url) {
return new Promise((resolve, reject) => {
instance.get(url,{
responseType:'blob'
})
.then(res => {
if (res.status === 200) {
resolve(res)
} else {
Message({
message: '数据错误,请重试!',
type: 'error'
})
}
})
.catch(() => {
// 请求失败会走catch,直接跳转到NotFound页面
router.push({
path:'/notFound'
})
})
})
}
3.若是下载一个http链接文件,直接创建a标签:
const elink = document.createElement('a');
elink.style.display = 'none';
elink.href = pathUrl + '/report/download/report_column';
document.body.appendChild(elink);
elink.click();
URL.revokeObjectURL(elink.href); // 释放URL 对象
document.body.removeChild(elink);
网友评论