上传单个文件的坑
常用需求:只允许上传一个文件,且要始终显示当前选择的文件,后选的文件要覆盖之前的文件
如果只上传一个文件,建议不要用 limit = '1' ,这是个大坑,如果设置了limit = '1',当你选择第二个文件
的时候是不会触发on-change函数的,你可以设置on-exceed函数来提醒用户先删除再选择,但这并不友好
所以最好的解决办法:
<el-upload
class="upload-demo"
ref="upload"
action="" //填自己的路径
:show-file-list="true"
:on-change="fileChange"
:file-list="fileList"
accept=".sec" //自定义接受的文件类型
:auto-upload="false" // 不自动上传
>
<el-button>选择文件</el-button>
</el-upload>
//如果这里有个上传按钮的话
<el-button @click='uploadFile'>上传文件</el-button>
data() {
return {
fileList: []
}
}
methods: {
fileChange (file, fileList) {
// 这是关键一句
if (fileList.length > 0) {
this.fileList = [fileList[fileList.length - 1]]
}
// 根据自己项目需求吧,我们这个要写入的,
//var reader = new FileReader()
//reader.readAsText(file.raw)
//reader.onload = function (e) {
//sessionStorage.setItem('files', reader.result)
//}
//},
uploadFile () {
this.$refs.upload.submit()
}
}
/*修改upload组件样式,如果不修改,会出现不友好的动画效果,*/
.upload-demo {
display: flex;
}
.el-list-enter-active,
.el-list-leave-active {
transition: none;
}
.el-list-enter,
.el-list-leave-active {
opacity: 0;
}
.el-upload-list {
height: 40px;
}
写的不好望见谅,有问题可以私聊,我们一同进步