Search code examples
angularjsng-file-upload

Angularjs Show Image preview only if selected file is image


Here is my AngularJS code to show image preview when user selects the 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 is displaying thumb image preview when image is selected

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

Now problem is when I'm selecting the image, image thumb displays correctly but when I'm selecting pdf, doc or any other file format, it displays crack image thumb. How can I put some AngularJs condition here such that it should display image thumb only if image is selected, otherwise it displays nothing.


Solution

  • solved it by adding an onChange to your input and doing a check for the file extension in the 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