最近写项目遇到了上传文件显示进度条问题,后来网上学习了一波,最后整理了一下自己成功的方案。
每一部分代码如下:
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
里的data
内容:
vue
里的 methods
内容:
下载导入模板:
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
并展示出来。需要进度条的可以用element-ui
的 Progress
进度条,如下:
上述内容中,需要放入后端接口的地方我都标注了一下~
样式可根据自己需要去设置~