Angularjs Show Image preview only if selected file

2019-02-18 22:51发布

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.

2条回答
贪生不怕死
2楼-- · 2019-02-18 23:25

I have removed the function and its working 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;
    }

}
查看更多
等我变得足够好
3楼-- · 2019-02-18 23:46

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

查看更多
登录 后发表回答