<template>
<div>
<!-- 解决思路:设置limit可以上传2个文件,但上传2个文件成功后,默认把第一个文件去掉,只保留最后上传的文件 -->
<el-upload action="#" :auto-upload="true" :limit="2" :on-change="changeFiles" :before-upload="beforeUpload" :on-success="uploadSuccess" :on-error="uploadError" :on-remove="removeFilePath" :on-exceed="onExceed" ref="myUpload">
<el-button size="small" slot="trigger">上传文件</el-button>
<div slot="tip" class="el-upload__tip" v-if="showFileTips">
{{
"只支持上传" + getAcceptFileTips + "文件"
}}
</div>
</el-upload>
</div>
</template>
<script>
export default {
name: 'myUploadCompoent',
data() {
return {}
},
model: {
prop: 'fileInfo',
event: 'change'
},
props: {
fileInfo: Object,
customFileTips: { type: String, default: '' },
showFileTips: { type: Boolean, default: true },
disabled: {
type: Boolean,
default: false
},
//接收的文件类型
acceptFileArr: {
type: Array,
default: function () {
return ['.txt', '.doc']
}
},
},
computed: {
getAcceptFileTips() {
return this.acceptFileArr.join(' ')
}
},
mounted() {},
methods: {
beforeUpload(res) {
// 获取当前上传文件的类型
if (this.acceptFileArr?.length > 0 && res?.name) {
let nowFileType = ''
try {
nowFileType = res.name.substring(res.name.lastIndexOf('.'))
} catch (error) {
nowFileType = ''
}
if (nowFileType && this.acceptFileArr.indexOf(nowFileType) === -1) {
//给出提示:请上传正确格式的文件
return false
}
}
return true
},
changeFiles(file, fileList) {
//解决思路:设置limit可以上传2个文件,但上传2个文件成功后,默认把第一个文件去掉,只保留最后上传的文件
if (fileList.length > 1) {
fileList.shift()
}
},
uploadError() {
// 文件上传失败
},
uploadSuccess(res, file, fileList) {
if (res?.data?.path) {
this.fileInfo.path = res.data.path
this.$emit('fileChange', this.fileInfo)
}
},
onExceed(res, file) {},
}
}
</script>
<style lang="less" scoped></style>
element upload文件上传第二次上传失败的解决方法
于 2024-02-27 11:39:33 首次发布
文章介绍了如何在Vue的el-upload组件中,设置文件上传的限制数量为2,并解决上传后默认保留最后一个文件的问题。通过before-upload钩子判断文件类型并提供错误提示,changeFiles方法处理文件列表。
1万+

被折叠的 条评论
为什么被折叠?



