3

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.

  • Possible duplicate of [HTML input type=file, get the image before submitting the form](http://stackoverflow.com/questions/5802580/html-input-type-file-get-the-image-before-submitting-the-form) – tao Feb 21 '17 at 23:42
  • http://stackoverflow.com/questions/5697605/limit-the-size-of-an-file-upload-html-input . Shows you how to achieve this using javascript. – Zze Feb 21 '17 at 23:43
  • 1
    Possible duplicate of [Check image width and height before upload with Javascript](http://stackoverflow.com/questions/8903854/check-image-width-and-height-before-upload-with-javascript) – Sohaib Feb 21 '17 at 23:43

2 Answers2

3

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")
    }
  };

};
arc
  • 3,984
  • 4
  • 31
  • 40
1

Since you're having a file there, you will first need to load it into an Image. After that, you can check the height and width to see if it fits your needs. Note that a server-side verification is necessary too, because JavaScript can be tricked. Browser support also varies.

1. Step: Handle `changed`-event
2. Step: Create Image, handle onload
3. Step: Load the file into the Image object

Demonstration: http://codepen.io/NikxDa/pen/apegZa

NikxDa
  • 3,777
  • 1
  • 22
  • 43
  • So whoever downvoted this could at least be kind enough to share the reason with me, so I can update the post accordingly. – NikxDa Feb 22 '17 at 00:00