Element中多文件上传(el-upload组件)

Element-ui官网(适用于vue2.0)

解决多文件上传,自定义方法调用多次接口

  • 1、将 <el-upload> 组件中的 auto-upload 设置为 false
  • 2、使用 on-change钩子对上传方法进行重写。
  • 3、在方法的最后添加 return false
完整代码:
<template>
	<el-upload
	 ref="uploadImg"
	 action
	 multiple
	 accept=".png,.jpeg,.jpg"
	 list-type="picture-card"
	 :auto-upload="false"
	 :file-list="uploadImg"
	 :on-change="handleChangeImg"
	>
	 <span class="text">点击上传图片</span>
	</el-upload>
</template>
<script>
export default {
	data() {
    	return {
            imgType: ['png', 'jpeg', 'jpg'], // 图片的格式
			uploadImg: []  // 初始化存储 上传的多个图片 的数据
		}
	},
	methods: {
	    // 上传图片文件之前 对图片格式进行校验
	    beforeUploadImg(file) {
	      if (file.name) {
	        // 图片的格式限制,正确是true
	        let imgTypeIsRight = true
	        // 图片的大小限制,正确是false
	        let imgSizeIsRight = true
	        const nameType = file.name.split('.')
	        imgTypeIsRight = this.imgType.includes(nameType[nameType.length - 1])
	        imgSizeIsRight = file.size / 1024 / 1024 > 2
	        if (!imgTypeIsRight) {
	          this.$message.warning(`图片格式不正确`)
	        }
	        if (imgSizeIsRight) {
	          this.$message.warning(`图片大小不能超过2M`)
	        }
	        return imgTypeIsRight && !imgSizeIsRight
	      }
	    },
	    // 点击 上传图片按钮 后,将图片信息进行处理
	    handleChangeImg(singleFile, fileList) {
	    	// 对每一张图片都进行格式的校验
	        const fileFormat = this.beforeUploadImg(singleFile)
	        if (fileFormat) { // 图片格式校验无误
	          const hasImg = this.uploadImg.some( // 校验 当前的图片是否存储过
	            (imgItem) => imgItem.uid === singleFile.uid
	          )
	          if (!hasImg) { // 没有存储过
	            this.uploadImg.push({
	              uid: singleFile.uid,
	              url: singleFile.url,
	              pushUrl: '',
	              inputName: '',
	              inputUrl: '',
	              name: '',
	              file: singleFile
	            })
	          }
	        } else { // 格式校验失败,将这张图片移除
	          for (let i = 0; i < this.uploadImg.length; i++) {
	            if (this.uploadImg[i].uid === singleFile.uid) {
	              this.uploadImg.splice(i, 1)
	            }
	          }
	        }
	        return false
	    },
	}	
}
</script>
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值