【问题标题】:Do 3 unified checks做3次统一检查
【发布时间】:2018-09-13 10:19:42
【问题描述】:

我有一个包含 3 个文件输入字段的表单,但 Laravel 给了我这个问题:link

所以,我会在发送文件之前检查,最大分辨率为 2000x2000,我得到了这段代码并修改了,但它仍然报错,因为一个通过另一个。我想知道如何将这三张支票合二为一。

这是我的代码:

$("#personal").change(function() { 
  var fr = new FileReader;
  fr.onload = function() {
    var imgPersonal = new Image;
    imgPersonal.onload = function() {
      if (imgPersonal.width > 2000 &&  this.height > 2000) {
        $("#submitDocs").attr("disabled", true); 
      } else {
        $("#submitDocs").removeAttr("disabled");
      }
    };
    imgPersonal.src = fr.result;
  };
  fr.readAsDataURL(this.files[0]);
});

$("#self").change(function() { 
  var fr = new FileReader;
  fr.onload = function() {
    var imgSelf = new Image;
    imgPersonal.onload = function() {
      if (imgSelf.width > 2000 &&  this.height > 2000) {
        $("#submitDocs").attr("disabled", true);
      } else {
          $("#submitDocs").removeAttr("disabled");
        }
      }
    };
    imgSelf.src = fr.result;
  };
  fr.readAsDataURL(this.files[0]);
});

$("#address").change(function() { 
  var fr = new FileReader;
  fr.onload = function() {
    var imgAddress = new Image;
    imgPersonal.onload = function() {
      if (imgAddress.width > 2000 &&  this.height > 2000) {
        $("#submitDocs").attr("disabled", true); 
      } else {
          $("#submitDocs").removeAttr("disabled");
        } 
      }
    };
    imgAddress.src = fr.result;
  };
  fr.readAsDataURL(this.files[0]);
});

【问题讨论】:

  • 您的代码有一些语法错误 - 方括号/圆括号并不匹配。此外,在调用构造函数时,请使用括号。

标签: javascript php jquery laravel upload


【解决方案1】:

尝试将所有重复的代码放在一个函数中,与DRY 保持一致,并保留一个持久对象来检查是否有任何上传的图像无效:

const checks = {
  personal: true,
  self: true,
  address: true,
};

function validate(file, checkAttr) {
  const fr = new FileReader();
  fr.readAsDataURL(file);
  fr.onload = function() {
    const img = new Image();
    img.onload = () => {
      if (img.width > 2000 || img.height > 2000) checks[checkAttr] = true;
      else checks[checkAttr] = false;
      if (checks.personal && checks.self && checks.address) $("#submitDocs").removeAttr("disabled");
      else $("#submitDocs").attr("disabled", true);
    }
    img.src = fr.result;
  }
}

$("#personal").change(function() {
  validate(this.files[0], 'personal');
});

// other handlers

【讨论】:

    【解决方案2】:

    @CertainPerformance,谢谢,我能按照你的方式做,我做了这个功能,我使用了 onblur = "btndisabled();"在每个输入中

    function btndisabled() {
            var sizePersonal = personal.files[0].size;
            var sizeSelf = self.files[0].size;
            var sizeAddress = address.files[0].size;
            if (sizePersonal < 1000000 && sizeSelf < 1000000 && sizeAddress < 1000000) {
              $("#submitDocs").removeAttr("disabled");
            } else {
              alert('File larger than 1MB');
              $("#submitDocs").attr("disabled", true);
            }
          }
    

    【讨论】:

      最近更新 更多