Angularjs Show image preview only if selected file is image

Here is my AngularJS code to show an image preview when the user selects a file

  <form action="<?php echo $this->getFormAction();?>" id="contactproForm" method="post" ng-app="myApp" ng-controller="myCtrl" enctype="multipart/form-data">

     <label for="file"><?php echo Mage::helper('contactpro')->__('Attachment') ?></label>

    <div class="input-box">
       <input  type="file" id="file" class="input-text" ngf-select ng-model="picFile" name="attachement" accept="image/png, image/jpeg, image/jpg, application/msword, application/vnd.ms-excel, application/pdf " />
    </div>

    <label for="file"><?php echo Mage::helper('contactpro')->__('Image Preview') ?></label>
    <img ng-show="picFile[0] != null" ngf-src="picFile[0]" class="thumb">

   </form>

      

This line displays thumb preview when selecting an image

   <img ng-show="picFile[0] != null" ngf-src="picFile[0]" class="thumb">

      

Now the problem is when I select the image, the thumb image is displayed correctly, but when I select pdf, doc or any other file format, it shows the crack image. How can I put some kind of AngularJs condition here so that it only displays the thumb of the image if the image is selected, otherwise it doesn't display anything.

+3


source to share


2 answers


solved it by adding onChange to your input and doing file extension check in controller.

<div class="input-box">
  <input type="file" id="file" class="input-text" ngf-change="onChange($files)" ngf-select ng-model="picFile" name="attachement" accept="image/png, image/jpeg, image/jpg, application/msword, application/vnd.ms-excel, application/pdf " />
</div>
<img ng-show="isImage(fileExt)" ngf-src="picFile[0]" class="thumb">


$scope.isImage = function(ext) {
      if(ext) {
        return ext == "jpg" || ext == "jpeg"|| ext == "gif" || ext=="png"
      }
    }

      



See Updated Plunkr

+4


source


I removed the function and it works without console error



<div class="input-box">
<input type="file" id="file" class="input-text" ngf-change="onChange($files)" ngf-select ng-model="picFile" name="attachement" accept="image/png, image/jpeg, image/jpg, application/msword, application/vnd.ms-excel, application/pdf " />
</div>
<img ng-show="isImage" ngf-src="picFile[0]" class="thumb">

$scope.onChange = function (files){

    if(files[0] == undefined) return;

    $scope.fileExt = files[0].name.split(".").pop();

    if($scope.fileExt.match(/^(jpg|jpeg|gif|png)$/))
    {
        $scope.isImage = true;
    }
    else
    {
        $scope.isImage = false;
    }

}

      

0


source







All Articles