最近写项目的时候遇到了上传文件时进度条显示的问题。 后来在网上研究了一下,终于整理出了自己的成功方案。
各部分代码如下:
HTML 代码:
<template>
<el-upload
class="upload-demo"
action="在这里写上传的接口"
:show-file-list="false"
:before-upload="beforeUpload"
:http-request="handleRequest">
<el-button size="small" type="primary" v-if="!progressPercent">点击上传</el-button>
<el-button size="small" type="primary" v-if="progressPercent">上传中... {{progressPercent}}%</el-button>
<div slot="tip" class="el-upload__tip">只能上传Excel文件,且不超过10MB</div>
</el-upload>
</template>
vue中的数据内容:
vue中的方法内容:
下载导出模板:
download() {
window.open("在这里写下载的接口");
},
上传前校准文件大小和文件类型:
beforeUpload(file) {
const isLt10M = file.size / 1024 / 1024 < 10;
if (['application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'].indexOf(file.type) === -1) {
this.$message({
type: 'error',
message: "只能上传Excel文件~",
});
return false;
};
if (!isLt10M) {
this.$message({
type: 'error',
message: "文件不能超过10MB~",
});
return false;
}
},
处理上传Excel操作:
async handleRequest(data) {
let formdata = new FormData();
formdata.append('file', data.file);
const config = {
onUploadProgress: event => {
// event.loaded:已上传文件大小
// event.total:被上传文件的总大小
this.progressPercent = Number((event.loaded / event.total * 100) | 0);
}
};
let uploadRes = await http.post('这里是上传操作的接口', formdata, config);
// console.log('uploadRes',uploadRes);
if ('这里写自己判断成功的条件') {
this.progressPercent = 0;
this.$message({
type: 'success',
message: "上传成功~",
});
} else {
this.progressPercent = 0;
this.$message({
type: 'error',
message: "上传失败~",
});
}
},
}
我这里不显示进度条,而是获取当前进度数据progressPercent并显示。 如果需要进度条elementui下载本地文件elementui下载本地文件,可以使用element-ui的Progress进度条,如下:
上面的内容中,我已经标记了需要安装前端插座的地方了~
风格可以根据自己的需要来设定~
发表评论