当前位置: 代码迷 >> 综合 >> 前台Vue使用axios实现文件下载功能
  详细解决方案

前台Vue使用axios实现文件下载功能

热度:16   发布时间:2024-01-25 20:47:13.0

1、页面

<template><div><button @click="downFile">下载doc文件</button></div>
</template>

2、get请求

downFile(){axios({method:'get',url:url,responseType:'blob',}).then(resp => {this.download(resp)}).catch((error) => {})
}

3、post请求

axios({method: 'post',url: 'api/user/',data: data,responseType: 'blob'
}).then(resp => {this.download(resp)
}).catch((error) => {
})

4.处理函数

download (data) {if (!data) {return}let url = window.URL.createObjectURL(new Blob([data]))let link = document.createElement('a')link.style.display = 'none'link.href = urllink.setAttribute('download', 'test.doc')document.body.appendChild(link)link.click()}