一、实现思路:html
html5 中,在 a 标签上添加 download 属性能够实现文件下载。前端
<a download="文件名" href="文件下载接口地址"></a> html5
二、在此次项目中,点击非a标签按钮下载文件,经过建立a标签来实现。ios
<script> export default { data() { return { downFileName: 'user_dowm', // 自定义下载的文件名 } }, methods:{
// 点击下载事件 downLoadFail(data) { this.$axios({ headers: { 'Content-Type': 'application/json' }, url: '/user/download', data: data, responseType: 'blob', method: 'get' }).then(res => { if (typeof window.chrome !== 'undefined') { // Chrome version const blob = new Blob([res], { type: 'application/vnd.ms-excel' }) const urls = window.URL.createObjectURL(blob) const a = document.createElement('a') // 生成虚拟a标签 a.href = urls a.download = this.downFileName + '.xlsx' a.click() document.body.removeChild(a) // 下载完成移除元素 window.URL.revokeObjectURL(urls) // 释放掉blob对象 } else if (typeof window.navigator.msSaveBlob !== 'undefined') { // IE version const blob = new Blob([res], { type: 'application/force-download' }) window.navigator.msSaveBlob(blob, this.downFileName) } else { // Firefox version const file = new File([res], this.downFileName, { type: 'application/force-download' }) window.open(URL.createObjectURL(file)) } }).catch(err => { console.log(err) }) } } } </script>
注:发现一篇实用的前端下载文件的参考,贴上~chrome