Kamikaza Kamikaza - 4 months ago 8
jQuery Question

HTML5 Form Check image width and height and alert if bigger

EDIT

NOT A DUPLICATED, THE SOLUTIONS GIVEN ON OTHERS POSTS ARE NOT THE SAME AND THEY ARE NOT WORKING NEITHER, BUT BECAUSE SOME MODERATORS JUST DO NOT READ BUT JUST WANT TO SHOW POWER THEY JUST MARK IT AS DUPLICATED...

I am using the following form to upload images. It is working fine but because it is a store and I want the catalog of products to looks nice I need the images uploaded to be exactly 200px width and 200px height. If the image is bigger in width or height I need to show an alert so the uploader chose another image or edit the one he is trying to upload.

<form action="upload" enctype="multipart/form-data" method="post">

Upload image:
<input id="image-file" type="file" name="file" />
<input type="submit" value="Upload" />

<script type="text/javascript">
$('#image-file').bind('change', function() {
alert('here we have to do something');
});
</script>

</form>

Answer

Possible duplicate? Taken from answer here and adapted for you:

Is it possible to check dimensions of image before uploading?

I would agree with above answer and do it on the form submit:

$( document ).ready(function() {
$("#ImageForm").submit( function( e ) {
    var form = this;
    e.preventDefault(); //Stop the submit for now
                                //Replace with your selector to find the file input in your form
    var fileInput = $(this).find("#image-file")[0],
        file = fileInput.files && fileInput.files[0];
	console.log(file)
    if( file ) {
        var img = new Image();

        img.src = window.URL.createObjectURL( file );

        img.onload = function() {
            var width = img.naturalWidth,
                height = img.naturalHeight;

            window.URL.revokeObjectURL( img.src );

            if( width <= 200 && height <= 200) {
                form.submit();
            }
            else {
                alert('too big');
            }
        };
    }
    else { //No file was input or browser doesn't support client side reading
        form.submit();
    }

});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="ImageForm" method="post">

    Upload image:
    <input id="image-file" type="file" name="file" />
    <input type="submit" value="Upload" />
</form>

As the answer in my link says you need to also check this server side as a) you cannot ever trust the client b) older browsers might not work.

Comments