Vue前台实现文件下载
js工具类代码
import axios from 'axios'
const baseUrl = process.env.VUE_APP_BASE_URL
const downLoadZipFile = (params, path) => {
return axios({
method: 'post',
url: baseUrl + path,
data: params,
responseType: 'blob'
})
}
const downloadFile = res => {
debugger
//eslint-disable-next-line
let blob = new Blob([res.data], { type: 'application/zip' })
//对于<a>标签,只有 Firefox 和 Chrome(内核) 支持 download 属性
//IE10以上支持blob但是依然不支持download
if ('download' in document.createElement('a')) {
//支持a标签download的浏览器
const link = document.createElement('a') //创建a标签
link.download = decodeURI(res.headers['content-disposition'].split('=')[1]) //a标签添加属性
link.style.display = 'none'
link.href = URL.createObjectURL(blob)
document.body.appendChild(link)
link.click() //执行下载
URL.revokeObjectURL(link.href) //释放url
document.body.removeChild(link) //释放标签
} else {
navigator.msSaveBlob(blob, res.headers['content-disposition'].split('=')[1])
}
}
const downloadStaticFile = (fileName, filePath) => {
return axios
.get(filePath, {
//静态资源文件夹public
responseType: 'blob'
})
.then(response => {
const url = window.URL.createObjectURL(new Blob([response.data]))
if ('download' in document.createElement('a')) {
const link = document.createElement('a')
link.href = url
link.setAttribute('download', fileName)
document.body.appendChild(link)
link.click()
} else {
navigator.msSaveBlob(new Blob([response.data]), fileName)
}
})
.catch(error => {
console.log('error:' + JSON.stringify(error))
})
}
const downloadExcel = res => {
debugger
//eslint-disable-next-line
let blob = new Blob([res.data], { type: 'application/zip' })
//对于<a>标签,只有 Firefox 和 Chrome(内核) 支持 download 属性
//IE10以上支持blob但是依然不支持download
if ('download' in document.createElement('a')) {
//支持a标签download的浏览器
const link = document.createElement('a') //创建a标签
link.download = decodeURI(res.headers['content-disposition'].split('=')[1]) //a标签添加属性
link.style.display = 'none'
link.href = URL.createObjectURL(blob)
document.body.appendChild(link)
link.click() //执行下载
URL.revokeObjectURL(link.href) //释放url
document.body.removeChild(link) //释放标签
} else {
navigator.msSaveBlob(blob, res.headers['content-disposition'].split('=')[1])
}
}
export { downLoadZipFile, downloadFile, downloadStaticFile, downloadExcel }
vue文件里导入js工具类
下载按钮调用downloadStaticFile
<el-button
type="primary"
@click="download"
>
<a
id="download"
href="javascript:void(0);"
style="color: #fff; textdecoration: none"
>下载模板</a>
</el-button>
downloadStaticFile方法的默认路径参数是public,这边传入路径时定位到files里面,模板放到files路径下
download() {
downloadStaticFile(
'***模板.xls',
'files/***.xls'
)
},