vue+axios实现文件下载及实现文件下载及vue中使用中使用axios的实例的实例
功能:点击导出按钮,提交请求,下载excel文件;
第一步:跟后端童鞋确认交付的接口的response header设置了
以及返回了文件流。
第二步:修改axios请求的responseType为blob,以post请求为例:
axios({
method: 'post',
url: 'api/user/',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
},
responseType: 'blob'
}).then(response => {
this.download(response)
}).catch((error) => {
})
第三步:请求成功,拿到response后,调用download函数(创建a标签,设置download属性,插入到文档中并click)
methods: {
// 下载文件
download (data) {
if (!data) {
return
}
let url = window.URL.createObjectURL(new Blob([data]))
let link = document.createElement('a')
link.style.display = 'none'
link.href = url
link.setAttribute('download', 'excel.xlsx')
document.body.appendChild(link)
link.click()
}
}
下面在通过实例代码看下下面在通过实例代码看下vue中使用中使用axios
1.安装axios
npm:
$ npm install axios -S
cdn:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
2.配置配置axios
在项目中新建api/index.js文件,用以配置axios
api/index.js
import axios from 'axios';
let http = axios.create({
baseURL: 'http://localhost:8080/',
withCredentials: true,
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
评论0