Neeraj Kumar
Neeraj Kumar

Reputation: 226

Validate the image file dimensions in input on Client side AngularJS

I wanted to validate an image dimensions before uploading it to server on client side itself. I tried finding solution for it, but i could find solutions with img.Onload(), which i am not looking for.

I just want the user to select the image from
<input id="selectThumb" name="myImage" type="file" accept="image/*" onchange="angular.element(this).scope().fileName(this)" </input>
and after selecting the file, only Name should be displayed and some alert should be displayed if the image is bigger than 172X152px. I am not previewing the image or anything. "fileName(this)" function gives me the name of the image file, i am unable to get the dimensions of image and thus can't validate them. PS, I have defined this function in my directive.

Once again, I want to show an alert when the user selects a file, if his file is not eligible to get uploaded i.e. bigger than 172X152px. I am not loading the image file on my page or previewing it.

Upvotes: 0

Views: 2848

Answers (1)

David Votrubec
David Votrubec

Reputation: 4156

I am afraid you will HAVE TO use Image.onLoad. But dont worry the image does not need to shown anywhere.

Example is here Getting Image Dimensions using Javascript File API

    var fr = new FileReader;

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

        img.onload = function() {
            //TODO: Add your validation here
            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

Upvotes: 3

Related Questions