这次在做了项目的时候,选用的是element ui 中的 upload组件,确实比较方便,该想到的功能,组件基本也都封装好了,但是有一条还是有点问题,就是只能上传一个文件的时候,上传另一个文件,实现覆盖之前的文件,我之前的想法是给一个limit=1限制,然后再on-exceed钩子函数里去处理解决,试了好久发现不是那么容易,然后耍了个小聪明,下面贴出源码:
<el-form-item label="上传算法文件" prop="file2">
<el-upload
ref="upload"
class="upload-demo"
:action="url3"
:on-preview="handlePreview"
:on-remove="handleRemove"
:file-list="fileList"
:auto-upload="false"
:data="form"
:limit="1"
:before-upload="beforeUpload"
:on-success="handleSucess"
:on-change="onChange"
:on-exceed="handleExceed"
accept=".xls,.xlsx"
>
<el-button slot="trigger" size="small">选择文件</el-button>
<div slot="tip" class="el-upload__tip">
仅支持扩展名:.xls, .xlsx
</div>
</el-upload>
</el-form-item>
handleExceed(files, fileList) {
this.$message.warning('超出1个文件,请先删除当前文件,再重新上传')
return false
},
这样让用户每次选择的时候,给出提示,无法选择,只能删除掉再选择,但这样其实没有从根本上解决问题。下面给出具体解决方法吧
<el-form-item label="上传算法文件" prop="file2">
<el-upload
ref="upload"
class="upload-demo"
:action="url3"
:on-preview="handlePreview"
:on-remove="handleRemove"
:file-list="fileList"
:auto-upload="false"
:data="form"
:before-upload="beforeUpload"
:on-success="handleSucess"
:on-change="onChange"
accept=".xls,.xlsx"
>
<el-button slot="trigger" size="small">选择文件</el-button>
<div slot="tip" class="el-upload__tip">
仅支持扩展名:.xls, .xlsx
</div>
</el-upload>
</el-form-item>
onChange(file, fileList) {
// console.log(file)
if (fileList.length > 0) {
this.fileList = [fileList[fileList.length - 1]]//这一步,是 展示最后一次选择文件
}
},
到这里,解决了本篇文章题目所提到的问题。