0

I have some code that i changed. It was prevusly to get file ext. I wannted it to get width of uploded image( before even clicking submit input ) and if it's too small giving alert. Problem is that i dont really know how i can connect this js code with html form.

<form id="add" method="POST" enctype="multipart/form-data" action="upload.php">
<input type="file" id= "filput" style="margin-bottom:30px; margin-top:20px;" name="file" size="40" />
</form>


$("#filput").on('change', function () {
    var w = $(this).width();
    if (w < 500) {
        alert("too small");
    } else {
        alert("big");
    }
});
Satpal
  • 132,252
  • 13
  • 159
  • 168
Baltrek
  • 97
  • 1
  • 1
  • 9
  • `$(this)` in your 'change' handler refers to the `#filput` element, not the image you uploaded. – Derek Feb 23 '14 at 11:53

1 Answers1

2

The this referrs to the input not the image. You have too use the HTML5 file API.

You can use this example: How to get the image width from html 5 file API

Code example: copied from: Getting Image Dimensions using Javascript File API

$("#filput").on('change', function () {
     var fr = new FileReader;

    fr.onload = function() { // file is loaded
        var img = new Image;

        img.onload = function() {
            alert(img.width); // image is loaded; sizes are available
        };

        img.src = fr.result; // is the data URL because called with readAsDataURL
    };

    fr.readAsDataURL(this.files[0]); // I'm using a <input type="file"> for demonstrating
});
Community
  • 1
  • 1
Niels
  • 48,601
  • 4
  • 62
  • 81
  • I would discourage you from using FileReader for this task. You run the risk of exhausting your browser's memory, not to mention the fact that this is an incredibly inneficient operation, especially when a large file is involved. Instead, use URL.createObjectURL, passing in the file or blob. Then, set the result of this call to the src attr of the img. – Ray Nicholus Feb 23 '14 at 14:34