How to validate an image size on a form

Hello,
I am building a form and I will have a file upload for images, I want to have them upload at a certain size; how can I make sure images don’t upload if size is bigger?

Thank you in advance

You could do this using a javascript either for file size in kb or dimensions… maxium width or height

For file size in kb (your file input to have id of uploadImage):

var fileUpload = document.getElementById("uploadImage");
fileUpload.addEventListener("change", function () {
  if (typeof fileUpload.files != "undefined") {
    var size = parseFloat(fileUpload.files[0].size / 1024).toFixed(2);

    if (size <= 2048) {
      alert("Your file is less than 2MB at: " + size + " KB.");
        //do something here if less
    } else {
      alert("Your file is more than 2MB at: " + size + " KB.");
         //do something here if more
    }
  } else {
    alert("File Not Supported");
  }
});

For Dimensions (again your file input to have id of uploadImage):
Set to check if width or height is less than 999

var fileUpload = document.getElementById("uploadImage");

fileUpload.addEventListener("change", function () {
  var reader = new FileReader();

  //Read the contents of Image File.
  reader.readAsDataURL(fileUpload.files[0]);
  reader.onload = function (e) {
    var image = new Image();
    image.src = e.target.result;
    image.onload = function () {
      var height = this.height;
      var width = this.width;
      if (height < 999 || width < 999) {
        alert("The image you uploaded is ok.");
        return false;
      }
      alert("height and width must not exceed 999px.");
      return true;
    };
  };
});

Make validation using javascript FileList property and instances of Image and FileReader, you can read more about them at mdn.

You cant verify resolution directly in input file since its just a file, you will have to create an Image(new Image) and read it using FileReader(new FileReader) :slight_smile:

Hello,
I just realize that the form it self has a max file upload of 10mb; thus this will do fine!

Thank you all!