使用el-upload在上传图片时,上传多张时,会出现重复问题,原因是on-change在监听文件变化时,是每次选择一个文件就要返回一次调用,例如:选择了两个文件,a.png,b.png就要返回两次,第一次返回[a.png],第二次返回[a.png,b.png],结果累加就是[a.png,a.png,b.png],所以会造成重复,需要处理一下,只要最后一次调用
好了,上代码
js如下:
handleChange(file, fileList) {
let length = fileList.length;
//this.maxlength在data中设置 即maxlength:0
this.maxlegth = Math.max(length, this.maxlegth);
setTimeout(() => {
if (length !== this.maxlegth) {
console.log("不是最大长度");
} else {
console.log("最大长度", length);
this.files = fileList;
for (var i = 0; i < this.files.length; i++) {
this.formData.append("files", this.files[i].raw);
console.log("文件:", this.files[i].raw);
}
}
});
},
标签代码如下:
<el-form-item label="上传图片:" :label-width="formLabelWidth">
<el-upload
class="uploadImage"
drag
action="#"
ref="uploadFile"
name="files"
multiple
:on-change="handleChange"
:auto-upload="false"
:http-request="httprequest"
:before-upload="beforeUpload"
>
<i class="el-icon-upload"></i>
<div class="el-upload__text">
将文件拖到此处,或<em>点击上传</em>
</div>
</el-upload>
</el-form-item>