console
<template>
<div class="custom-upload">
<el-upload
ref="uploadRef"
:auto-upload="false"
:action="''"
:show-file-list="false"
:http-request="customRequest"
:multiple="true"
:before-upload="beforeUpload"
:on-change="handleChange"
:on-success="handleSuccess"
:on-error="handleError"
:accept="getAcceptAttribute()"
>
<el-button type="primary" @click="triggerFileInput">选择文件</el-button>
</el-upload>
</div>
</template>
<script>
export default {
props: {
acceptedFileExtensions: {
type: Array,
default: () => []
}
},
data() {
return {
currentFile: null,
progressPercent: 0,
uploading: false,
uploadCompleted: false,
cancelToken: null,
progressStatus: 'success'
}
},
computed: {
formattedSize() {
if (!this.currentFile) return ''
const size = this.currentFile.size
if (size > 1024 ** 2) {
return `${(size / 1024 ** 2).toFixed(1)} MB`
}
return `${Math.round(size / 1024)} KB`
}
},
mounted () {
console.log('mounted element ui 上传组件')
},
methods: {
triggerFileInput() {
console.log('triggerFileInput')
},
async customRequest(options) {
console.log('options', options)
},
handleChange(file) {
console.log('el handleChange', file)
},
beforeUpload(file) {
console.log('beforeUpload')
const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'tiff'];
const fileExtension = file.name.split('.').pop().toLowerCase();
if (this.acceptedFileExtensions.length === 0) {
if (imageExtensions.includes(fileExtension)) {
this.$message.error('不支持上传图片文件');
return false;
}
return true;
}
if (!this.acceptedFileExtensions.includes(fileExtension)) {
this.$message.error(`不支持的文件后缀,仅支持:${this.acceptedFileExtensions.join(', ')}`);
return false;
}
return true;
},
handleSuccess() {
console.log('handleSuccess')
},
handleError(err) {
this.$message.error(err)
},
cancelUpload() {
console.log('cancelUpload')
},
generateFileId(file) {
return `${Date.now()}-${file.name}-${file.size}`
},
resetState() {
this.uploading = false
this.progressPercent = 0
this.currentFile = null
this.uploadCompleted = false
this.cancelToken = null
this.progressStatus = 'success'
},
getAcceptAttribute() {
if (this.acceptedFileExtensions.length > 0) {
return this.acceptedFileExtensions.map(ext => `.${ext}`).join(',');
}
return 'application/*,text/*';
}
}
}
</script>
<style scoped>
.custom-upload {
position: relative;
max-width: 500px;
}
.upload-progress {
margin-top: 15px;
padding: 12px;
background: #f8f9fa;
border-radius: 4px;
}
.upload-info {
margin-top: 8px;
display: flex;
justify-content: space-between;
align-items: center;
font-size: 12px;
color: #606266;
}
</style>