原理
axios 有一个方法:onDownloadProgress,它可以实时返回e.loaded 已经加载的值和e.total总数,
Math.round(e.loaded / e.total * 100) 通过计算刚好获取到已经处理的百分比。
实现代码
<template><div><button @click="downLoad(' 天农商-融联易云.pdf')">下载</button><p>下载进度:{{downLoadProgress}}</p><p>圆形:<el-progress type="dashboard" :percentage="downLoadProgress" :color="colors" /></p><p>横条:<el-progress :percentage="downLoadProgress" :color="colors" /></p></div>
</template><script setup>
import { ref } from 'vue';
import axios from 'axios'var downLoadProgress=ref(0) //定义下载进度
const colors = [{ color: '#f56c6c', percentage: 20 },{ color: '#e6a23c', percentage: 40 },{ color: '#5cb87a', percentage: 60 },{ color: '#1989fa', percentage: 80 },{ color: '#6f7ad3', percentage: 100 },
]//下载
var downLoad=function( fileName ){axios.post("/api-basic/download", null, {params: {filePath: '/redis-latest.tar',},responseType: 'blob',onUploadProgress: function(progressEvent) {// 上传进度监听回调函数},onDownloadProgress: function(e) {downLoadProgress.value = Math.round(e.loaded / e.total * 100) //实时获取最新下载进度}}).then(res=>{let link = document.createElement("a");link.href = URL.createObjectURL(res.data);link.download = fileName;document.body.appendChild(link);link.click();URL.revokeObjectURL(link.href);})
}
</script>