首页 > 语言 > JavaScript > 正文

vue 检测用户上传图片宽高的方法

2024-05-06 15:44:13
字体:
来源:转载
供稿:网友

需求:

用户可上传3-6张图片(第 1 2 3 张必须传),上传的图片必须是540 * 330 像素。

第一步,获取上传的图片的宽高。

初始化一个对象数组,宽高均设为0。

如果用户上传的图片没有上限,可以动态修改这个对象数组。

data:

  picArray:[  {   width:0,   height:0  },  {   width:0,   height:0  },  {   width:0,   height:0  },  {   width:0,   height:0  },  {   width:0,   height:0  },  {   width:0,   height:0  }  ],

HTML:

<myupload :keys="index" @getBase="getUpImg">    </myupload>

myupload是上传图片的组件,略。 

methods:

 getUpImg(imgurl, keys){  if(keys === 9){  this.submitData.logo_img = imgurl  this.logoImgCount = true  } else {  Vue.set(this.imgListArray,keys,imgurl)    this.$nextTick(function(){   let img = document.getElementById('picId' + keys)   // console.log(img)   let picArray = this.picArray   img.onload = function () {   console.log(keys)   console.log(this.naturalWidth)   console.log(this.naturalHeight)   let o = {    width: this.naturalWidth,    height: this.naturalHeight   }   Vue.set(picArray,keys,o)   console.log('picArray', picArray)   }  })  }   },

关键的代码用红色标出了。

值得注意的是:获取宽高必须用 this.$nextTick ,里面再写 img.onload 。this.naturalWidth 是图片原本的宽高。此时 this 指的是当前图片对象。

 第二步,提交之前检验图片的宽高。

methods:

 imageCheck(){  let checkboolean = true  let check = {  'width': [[540],[0,540]],  'height': [[330],[0,330]]  }  let f1 = function (num,index,type) {  let n = num  let i = index  let t = type  let b = false  // console.log(n,i,t)  for (let x = 0; x < check[type][i].length; x++) {   if (check[type][i][x] === num) {   // console.log('>>>>>>>>>>>>>' + check[type][i][x] + '===' + num + '>>>>>>>>>>>>>>>>' )   b = true   }     }  return b  }  for (let i = 0; i < this.picArray.length; i++) {  let cb = true  for (let x in this.picArray[i]) {   let number = this.picArray[i][x]   // console.log(x,number)   if (x === 'width' && i < 3) {   checkboolean = f1(number, 0, 'width')   if (!checkboolean) {    // console.log('=================',i,x,number,'return false')    cb = false    break   }   } else if (x === 'width' && i >= 3) {   checkboolean = f1(number, 1, 'width')   if (!checkboolean) {    // console.log('=================',i,x,number,'return false')    cb = false    break   }   } else if (x === 'height' && i < 3) {   checkboolean = f1(number, 0, 'height')   if (!checkboolean) {    // console.log('=================',i,x,number,'return false')    cb = false    break   }   } else if (x === 'height' && i >= 3) {   checkboolean = f1(number, 1, 'height')   if (!checkboolean) {    // console.log('=================',i,x,number,'return false')    cb = false    break   }   }  }  if (!cb) {   break  }  }  return checkboolean },// sumbit function...  if(!this.imageCheck()){  this.$message({   message: this.MASSAGE_imagecheck,   type: 'error'  });  return false  }  alert('可以传图')...            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选