博客 / 詳情

返回

vue 上傳圖片判斷大小尺寸

uploadImg(e, record, index) {
  const file = e.target.files[0];
  // 判斷上傳圖片的大小 限制
  if (file.size / 1024 < 1000) {
    const that = this;
    let imgWidth = "";
    let imgHight = "";
    // 限制圖片的尺寸 為2000*1500
    const isSize = new Promise(function(resolve, reject) {
      const _URL = window.URL || window.webkitURL;
      const img = new Image();
      img.onload = function() {
        imgWidth = img.width;
        imgHight = img.height;
        const valid =
          img.width === parseInt(2000) && img.height === parseInt(1500);
        valid ? resolve() : reject();
      };
      img.src = _URL.createObjectURL(file);
    }).then(
      () => {
        const formData = new FormData();
        formData.append("files", file);
        that.loading = true;
        // 這裏是調取接口
        接口名字(formData)
          .then(res => {
              // 接口成功操作啥的
              that.$message.success("圖片上傳成功");
    
          })
          .finally(() => {
            that.loading = false;
          });
      },
      () => {
        // 圖片尺寸不對 提示
        this.$message.info(
          `圖片尺寸應為2000x1500,當前圖片尺寸為${imgWidth}x${imgHight}`
        );
        return Promise.reject();
      }
    );
  } else {
    this.$message.info("圖片最大1000k");
  }
}
user avatar
0 位用戶收藏了這個故事!

發佈 評論

Some HTML is okay.