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.
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.
Share Improve this question asked Feb 21, 2017 at 23:36 Betun Herrera AlanisBetun Herrera Alanis 992 silver badges10 bronze badges 3- Possible duplicate of HTML input type=file, get the image before submitting the form – tao Commented Feb 21, 2017 at 23:42
- stackoverflow./questions/5697605/… . Shows you how to achieve this using javascript. – Zze Commented Feb 21, 2017 at 23:43
- 1 Possible duplicate of Check image width and height before upload with Javascript – Sohaib Commented Feb 21, 2017 at 23:43
2 Answers
Reset to default 5This 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")
}
};
};
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