<template>
<!-- 文件上传-->
<div>
<el-upload
ref="uploadRef"
:accept="accept"
:action="url"
:auto-upload="false"
:data="fileOtherData"
:headers="headers"
:limit="limit"
:file-list="nowFile"
:show-file-list="true"
:on-success="handleAvatarSuccess"
:on-error="handleError"
>
<el-button size="small" type="primary">选择文件</el-button>
</el-upload>
</div>
</template>
组件化开发(.vue文件) 下面是js代码
import storeApi from "@/utils/store"; // 获取token
export default {
name: "FileUpload",
props: {
limit: {
type: Number,
default: null
},
fileList: {
type: Array,
default: null
},
isEdit: {
type: Boolean,
default: false
},
// 允许上传的文件类型
accept: {
type: String,
default: '.pdf, .doc, .docx, .xls, .xlsx'
},
},
data() {
return {
url: `${process.env.VUE_APP_BASE_API}/file/anyone/upload`,
fileOtherData: {
bizId: '',
bizType: 'BASE_FILE',
isSingle: false
},
successArr: [],
nowFile: [],
};
},
computed: {
headers() {
return {
Authorization: "Bearer " + storeApi.get({ name: "token" }),
tenant: this.$store.getters.tenant
}
}
},
watch: {
fileList: {
handler(val){
if (val && val.length > 0){
this.nowFile = []
val.forEach((n) => {
const a = n;
a.name = n.originalFileName;
this.nowFile.push(a);
})
}
},
immediate: true,
deep: true
}
},
methods: {
handleAvatarSuccess(res) {
if (res && res.data){
this.successArr.push(res.data);
if (this.successArr.length === this.$refs.uploadRef.uploadFiles.length){
this.$emit('setId', this.successArr)
}
} else {
this.$message.error(res.message)
}
},
handleError(){
this.$message.error('附件上传失败!')
},
submitFile(){
this.successArr = [];
if (this.$refs.uploadRef.uploadFiles.length > 0){
this.isEdit === true ? this.handleEdit() : this.$refs.uploadRef.submit();
} else {
this.$message.warning('请选择附件!')
}
},
handleEdit(){
const delArr = [];
const h = this.$refs.uploadRef.uploadFiles.find((m) => m.url === this.nowFile[0].url)
if (typeof h !== 'undefined'){
this.successArr.push(this.nowFile[0])
}
const a = this.$refs.uploadRef.uploadFiles.find((n) => n.status === "ready")
if (typeof a !== 'undefined'){
this.handleDel(delArr);
this.$refs.uploadRef.submit();
} else {
this.handleDel(delArr);
this.$emit('setId', this.successArr)
}
},
}
}
引用该组件
<fileUpload
ref="fileRef"
:limit="1"
:file-list="fileList"
:is-edit="isEdit"
:accept="acceptType"
@setId="setIdAndSubmit"
/>
setIdAndSubmit(val) {
this.crud.form.templatePath = val[0].url;
this.crud.submitCU();
}, // 文件上传成功后执行该代码
submit() {
this.$refs.form.validate((valid) => {
if (valid) {
this.$refs.fileRef.submitFile();
}
});
}, // 弹窗点击确认时
总结:以上为方便自己反复采用的总结,如有错误可以指出,感谢!