先上效果图
<el-upload
:disabled="disableUpload"
class="upload-demo"
drag
action="#"
:show-file-list="false"
:file-list="fileList"
:http-request="httpRequest"
multiple
:on-change="handleChange"
>
<i class="el-icon-upload"></i>
<div class="el-upload__text">
将文件拖到此处,或<em v-if="!disableUpload">点击上传</em
><em v-else>上传中... ,请勿进行其他操作</em>
</div>
</el-upload>
data(){
return{
fileList: [],
percentage: 0,
percentNow: 0,
percentageTotal: 0,
disableUpload: false,
}
}
watch: {//解决弹窗比进度条快的问题
percentage(newval, old) {
if (newval == 100) {
setTimeout(() => {
this.loading = false;
this.$message({
message: "上传成功",
type: "success",
});
this.fileList = []
this.percentNow = 0
this.disableUpload = false
}, 1000);
}
}
},
自定义上传方法
async httpRequest(data) {
if (this.fileList.length == this.percentageTotal) {
this.percentage = 0
try {
this.loading = true;
let result = await this.uploadFileApi({
file: data.file,
})
this.percentNow+=1
if (result.data.code == 0) {
this.percentage = parseInt((this.percentNow / this.percentageTotal) * 100)
}//实际为当前已上传文件占总文件的百分比
} catch (error) {
this.loading = false;
this.$message.error("上传失败!");
}
}
},
//获取文件列表 上传中禁止再次上传
handleChange(file, fileList) {
this.fileList = fileList
this.disableUpload = true
},
上传方法
uploadFileApi(data) {
var formData = new FormData();
for (let key in data) {
formData.append(key, data[key]);
}
return axios({
url: this.$store.state.staticUrl + '/api/web/uploadFile',
method: 'post',
header: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
// onUploadProgress: (progressEvent) => {
// if (progressEvent.lengthComputable) {
// let complete = ((progressEvent.loaded / progressEvent.total) * 100) | 0;
// this.updateProgress(complete)
// }//此处为真实上传进度回调 但本地调试会跨域 nginx已经开启跨域的情况下也是
// },
data: formData,
})
},