首页 > 技术文章 > 在Vue项目里,利用Iview的upload组件,上传图片,在图片上传前,判断图片尺寸

ouyangxiaoyao 2020-07-16 20:13 原文

     handleBeforeUpload(file) {
      let _this = this
      return new Promise((resolve, reject) => {
        const check = _this.uploadList.length < _this.mutileUploadData.maxNum
        if (!check) {
          this.$Notice.warning({
            title: '最多上传' + this.mutileUploadData.maxNum + ''
          })
          reject(false)//重点
        }
        debugger
        let image = new Image()
        image.src = URL.createObjectURL(file)
        image.onload = () => {
          let width = _this.mutileUploadData.maxWidth
          let height = _this.mutileUploadData.maxHeight
          if (
            (width && image.width > width) ||
            (height && image.height > height)
          ) {
            this.$Modal.warning({
              title: '图片尺寸',
              content:
                '图片尺寸 ' +
                file.name +
                ' 太大,不能超过' +
                this.mutileUploadData.maxWidth +
                '*' +
                this.mutileUploadData.maxHeight +
                '',
              onOk() {}
            })
            reject(false)//重点
          }
          resolve(true)//重点
        }
        image.onerror = () => {
          reject()
        }
      })
    }

为什么要用Promise呢,因为image.onload()方法异步,

多次实验证明,iview的before-upload 中不支持 async,await,使用它们来做异步,return false 图片还是会被上传,后查证发现,是return 的是Promise对象,这里待研究补充

 参考文献;

https://blog.csdn.net/stevenxyy/article/details/101059772

https://www.jianshu.com/p/b4fd76c61dc9

 

上传前判断视频宽高比

          // 视频上传前处理
          // 宽高比例为16:9
          // 获取上传的视频的宽高
          return new Promise((resolve, reject) => {
            var videoUrl = URL.createObjectURL(file);
            var videoObj = document.createElement("video");

            videoObj.onloadedmetadata = function() {
              URL.revokeObjectURL(videoUrl);
              //   console.log(
              //     "视频宽高" + videoObj.videoWidth + videoObj.videoHeight
              //   );
              if (videoObj.videoWidth / videoObj.videoHeight != 16 / 9) {
                _this.$Modal.warning({
                  title: "视频不合规",
                  content: "上传的视频的宽高要按照标准的16:9的比例。",
                  onOk() {}
                });
                reject(false);
              }
              resolve(true);
            };
            videoObj.src = videoUrl;
            videoObj.load();
          });

 

推荐阅读