Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML file input accept images with certain dimension

I know this may require some javascript but how can I tell the input inside my form to reject images with size different than 64 x 64 without pressing the submit button.

<div class="form-group">
   <label for="plat_img">Icono</label>
   <input type="file" 
          accept="image/*"
          class="form-control" 
          id="plat_img">

The verification should happen as soon as the image is selected and if rejected, notify the user via an alert.

like image 976
Betun Herrera Alanis Avatar asked Jan 23 '26 23:01

Betun Herrera Alanis


1 Answers

This should do the job, you could now add a good error message as well.

var fileInput = document.getElementById("plat_img");
// listening on when someone selects a file
fileInput .onchange = function(e) {
  e.preventDefault();

  // get the file someone selected
  var file = fileInput.files && fileInput.files[0];

  // create an image element with that selected file
  var img = new Image();
  img.src = window.URL.createObjectURL(file);

  // as soon as the image has been loaded
  img.onload = function() {
    var width = img.naturalWidth,
      height = img.naturalHeight;

    // unload it
    window.URL.revokeObjectURL(img.src);

    // check its dimensions
    if (width <= 64 && height <= 64) {
      // it fits 
    } else {
      // it doesn't fit, unset the value 
      // post an error
      fileInput.value = ""
      alert("only 64x64 images")
    }
  };

};
like image 189
arc Avatar answered Jan 26 '26 13:01

arc