第一次用 element ui, 本人简略写了一个上传组件
1.BaseUpload.vue
<template>
<el-dialog
v-if="isDialog"
:visible="visible"
:title="title"
:width="width"
:before-close="beforeClose"
class="upload-dialog"
>
<el-upload class="upload-demo" drag action="#" :http-request="handleRequest" multiple>
<i class="el-icon-upload"></i>
<div class="el-upload__text">
<slot name="upload-operation-tips">
将文件拖到此处,或
<em> 点击上传 </em>
</slot>
</div>
<div class="el-upload__tip" slot="tip">
<slot name="template-download"> 请参照模板上传 </slot>
</div>
<div class="process_container" v-if="isProcessVisible">
<el-progress :type="type" :percentage="percentage" :status="status"></el-progress>
</div>
</el-upload>
</el-dialog>
</template>
<script>
import {upload} from "../../api/upload";
export default {
props: {
visible: {
type: Boolean,
default: false,
},
title: "",
actions: "",
width: "50%",
},
data() {
return {
type: "circle",
percentage: 0,
isProcessVisible: false,
status: null,
isDialog: false,
};
},
methods: {beforeClose() {
this.isDialog = false;
this.$emit("update:visible", false);
},
init() {
this.isDialog = true;
this.isProcessVisible = false;
this.percentage = 0;
this.status = null;
},
handleRequest(param) {
let fileObj = param.file;
let form = new FormData();
form.append("file", fileObj);
this.isProcessVisible = true;
upload(this.actions, form, this.uploadProcess).then((res) => {this.$emit("upload-callback", res);
this.beforeClose();});
return false; // 返回 false 不会主动上传
},
uploadProcess(pencent) {this.percentage = parseInt(pencent);
if (pencent == 100) {this.status = "success";}
},
},
watch: {
visible: {handler(val) {if (val) {this.init();
}
},
immediate: true,
},
},
};
</script>
<style scoped>
.upload-dialog {text-align: center;}
.upload-demo .el-upload-dragger {width: 100%;}
.process_container {
position: absolute;
top: 0px;
left: 0px;
width: 100%;
height: -webkit-fill-available;
background: white;
display: flex;
align-items: center;
align-content: space-between;
justify-content: center;
}
</style>
<style >
.upload-dialog .el-dialog {min-width: fit-content;}
</style>
2.axios 代码
let data = await axiosInstance.post(url, params, {headers: { "Content-Type": "multipart/form-data"},
timeout: uploadTimeout,
onUploadProgress: progressEvent => {let progressPercent = (progressEvent.loaded / progressEvent.total * 100);
callback(progressPercent);
}
}).catch(e => {return e;});
return data;
}