Prabhu S
Prabhu S

Reputation: 43

How to validate image File using Angular-js

am using angular-js for image file validation. i want to find out "is it image File or not"..here am compare the extension of file to identify the file is correct or not..

but my code is not work!..it doesn't show any error. am literally confused

anyone have the answers command here!..

Thanks in advance!

my Code is


<HTML>
 <HEAD>
  <TITLE>Validate image on upload</TITLE>
  <script src = "angular.min.js"></script>
  <body>
<center>
<div ng-app="prabhu"  ng-controller="mycontroller">


    Upload an image: <INPUT type="file" name="image_file" ng-model="fil.name">  
    //<h1>the file is {{val.validate())}}</h1>
 <p ng-bind="val.validate()"> <p>
 </div>
</center>
<script >

 var myapp = angular.module("prabhu",[]);
 myapp.controller("mycontroller",function($scope){

    $scope.val={            
        ref = ['jpg','jpeg','png'],         
        validate:function(){

            name = fil.name | lowercase;
            length = name.length();
            ext = name.LastIndexOf(".")+1;          
            ext1 = name.substring(ext,length);          
            //k = 0;            
            for (k=0 ; k <= 4;k++){
                if(ref[k]==ext1){
                    return "valid File Format";

                }
                //else
                //  return "invalid File Format";
            }           
            return "invalid File Format";
        }
    }; 
 });
 </script>
</BODY>

</HTML>

Upvotes: 3

Views: 10031

Answers (2)

guest271314
guest271314

Reputation: 1

my requirement is to select image files only!.

Try using accept attribute at input type="file" element

<input type="file" accept="image/*" />

Upvotes: 2

Khalid Hussain
Khalid Hussain

Reputation: 1694

Working fiddle.

As far as I know, no binding support for File Upload control.

HTML:

    <input type="file" ng-model="image" onchange="angular.element(this).scope().uploadImage(this.files)" />       

In controller:

$scope.uploadImage = function (files) {           
       var ext = files[0].name.match(/\.(.+)$/)[1];
       if(angular.lowercase(ext) ==='jpg' || angular.lowercase(ext) ==='jpeg' || angular.lowercase(ext) ==='png'){
        alert("Valid File Format");
       }  
       else{
        alert("Invalid File Format");
       }       
    }

Upvotes: 5

Related Questions