Check image width and height before upload with Javascript

前端 未结 8 864
情歌与酒
情歌与酒 2020-11-22 14:53

I have a JPS with a form in which a user can put an image:

Photo (max 240x240 and 100 kb):
8条回答
  •  北荒
    北荒 (楼主)
    2020-11-22 15:39

    In my view the perfect answer you must required is

    var reader = new FileReader();
    
    //Read the contents of Image File.
    reader.readAsDataURL(fileUpload.files[0]);
    reader.onload = function (e) {
    
    //Initiate the JavaScript Image object.
    var image = new Image();
    
    //Set the Base64 string return from FileReader as source.
    image.src = e.target.result;
    
    //Validate the File Height and Width.
    image.onload = function () {
      var height = this.height;
      var width = this.width;
      if (height > 100 || width > 100) {
        alert("Height and Width must not exceed 100px.");
        return false;
      }
      alert("Uploaded image has valid Height and Width.");
      return true;
    };
    

提交回复
热议问题