- 自定义上传访问后端接口
- 设置上传文件格式、大小、数量
- 设置文件名长度,不可重名
- 自定义文件列表渲染、文件删除
- 不重复提示el-message
<el-upload
action=""
:http-request="customUpload"
:before-upload="beforeFileAdd"
:on-exceed="handleExceed"
:file-list="fileList"
:limit="20"
accept=".doc,.docx,.txt"
multiple
:show-file-list="false"
:disabled="fileList.length>=20"
>
<div class="com-line-btn" :class="{'disable-btn':fileList.length>=20}">上传文件</div>
</el-upload>
//js
// 文件上传前
beforeFileAdd(file, fileList) {
// 检查文件名是否已存在
const isDuplicate = this.fileList.some(f => f.name === file.name)
if (isDuplicate) {
this.$message.error(`文件已存在,请重命名后上传`)
return false
}
// 文件名长度限制
const lastDotIndex = file.name.lastIndexOf('.')
const subStr = file.name.substring(0, lastDotIndex)
const isLtName = subStr.length <= 80
if (!isLtName) {
this.$message.error('文件名长度不能超过80个字符')
return false
}
// 文件大小限制
const isLt10M = file.size / 1024 / 1024 < 10
if (!isLt10M) {
if (document.getElementsByClassName('el-message').length > 0) {
return false
}
this.$message.error('上传文件大小不能超过 10MB!')
return false
}
const typeArr = ['.doc', '.docx', '.txt']
const isType = typeArr.includes(file.name.slice(file.name.lastIndexOf('.')).toLowerCase())
// 文件格式限制
if (!isType) {
if (document.getElementsByClassName('el-message').length > 0) {
return false
}
this.$message({
message: `上传文件格式必须为${typeArr}`,
type: 'warning'
})
return false
}
return true
},
// 文件个数限制
handleExceed(files, fileList) {
if (document.getElementsByClassName('el-message').length > 0) {
return false
}
this.$message.warning(`当前限制选择20个文件`)
},
// 自定义上传
customUpload(options) {
++this.rest
//页面加载
this.fileoneLoad = true
const formData = new FormData()
formData.append('file', options.file)
const p = {
body: formData
}
//调取后端接口
Api.uploadFile(p).then(res => {
if (res.data.code=== 1) {
--this.rest
if (this.rest === 0) {
this.fileoneLoad = false
}
if (document.getElementsByClassName('el-message').length > 0) {
return false
}
this.$message.success('文件上传成功!')
} else {
if (document.getElementsByClassName('el-message').length > 0) {
return false
}
this.$message.error('文件上传失败!')
}
}).finally(() => {
this.rest = 0
//文件列表查询
this.seachFileList()
this.fileoneLoad = false
})
},
// 文件列表查询
seachFileList() {
this.fileoneLoad = true
//调取后端接口
Api.getListFile().then(res => {
this.fileList = res.data
this.fileoneLoad = false
})
},
// 文件删除
delFileHandle(docId) {
this.$confirm('此操作将删除该文件, 是否继续?', '', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
Api.delFile().then(res => {
if (res.data.code=== 1) {
this.$message.success('删除成功!')
this.seachFileList()
}
})
}).catch(() => {})
}