axios 的 config 中封装了 onDownloadProgress(下载进度),onUploadProgress(上传进度),cancelToken(取消请求)的方法。
onUploadProgress 为上传进度方法,在上传文件时被实时调用,返回的 progress.loaded 为已经上传的文件大小,progress.total 是总文件大小。
<el-upload
class="upload"
name="file"
action="#"
:auto-upload="false"
:on-change="handleImport"
accept=".xls,.xlsx"
>
<el-button type="primary" :loading="buttonsLoading" icon="el-icon-upload2" size="mini"
>导入
</el-button>
</el-upload>
<el-progress v-if="uploadprogress" :percentage="uploadprogressPercentage"></el-progress>
axios({
method: 'post',
url,
headers: { Authorization: 'Bearer ' + getToken() },
timeout: 60 * 1000,
data: formData,
onUploadProgress: progress => {
if (progress.lengthComputable) {
this.uploadprogressPercentage = (progress.loaded / progress.total).toFixed(2) * 100 // 进度条百分比
}
},
})
点击导入按钮的时候会调用上传接口,上传文件时候就会触发 onUploadProgress 方法,在这个方法里面计算进度然后赋值给 el-progress 进度条的 percentage 就可以了。
|