axios
里的url
路径<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>文件分享</title>
<!-- 引入样式 -->
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
<style type="text/css">
* {
margin: 0;
padding: 0;
}
#app {
width: 100vw;
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
}
</style>
</head>
<body>
<div id="app">
<el-card shadow="hover">
<span style="margin-right: 10px;">文件名字:<el-input style="width:200px;" v-model="input"
placeholder="请输入内容"></el-input></span>
<el-button type="primary" @click="down" :disabled="disabled">下载文件</el-button>
</el-card>
</div>
<!-- js -->
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script>
<script type="text/javascript">
new Vue({
el: "#app",
data() {
return {
url: "",
input: "hotelmanagers",
disabled:false,
}
},
methods: {
// 文件下载
down() {
this.disabled = true;
axios({
method: "GET",
url: "./hotelmanagers.tar.gz",
responseType: ‘blob‘
}).then(res => {
let blob = new Blob([res.data], {
type: res.data.type
});
this.url = window.URL.createObjectURL(blob);
const a = document.createElement(‘a‘); //创建a标签
a.setAttribute(‘download‘, `${this.input}.tar.gz`); // 名字
a.setAttribute(‘href‘, this.url); // href链接
a.click(); // 自执行点击事件
document.body.appendChild(a); //插入body里
document.body.removeChild(a); //从body删除
this.disabled = false;
}).catch(res => {
this.$message.error("等待刷新,重新下载。")
setTimeout(()=>{
location.reload();
},800)
})
}
}
})
</script>
</body>
</html>
原文:https://www.cnblogs.com/1748sb/p/14505036.html