Angularjs 仅当所选文件为图像时才显示图像预览

Angularjs Show Image preview only if selected file is image

这是我的 AngularJS 代码,用于在用户选择文件时显示图像预览

  <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>

选中图像时,此行显示缩略图预览

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

现在的问题是,当我选择图像时,图像缩略图可以正确显示,但是当我选择 pdf、doc 或任何其他文件格式时,它会显示错误的图像缩略图。我如何在此处放置一些 AngularJs 条件,使其仅在选择图像时才显示图像缩略图,否则不显示任何内容。

通过向您的输入添加一个 onChange 并在控制器中检查文件扩展名来解决它。

<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

我已经删除了该功能及其正常运行而没有控制台错误

<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;
    }

}