4

这是我的 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 条件,使其仅在选择图像时才显示图像缩略图,否则不显示任何内容。

4

2 回答 2

6

通过在输入中添加 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"
      }
    }

查看更新的 Plunkr

于 2015-05-20T11:07:42.190 回答
0

我已经删除了该功能并且它的工作没有控制台错误

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

}
于 2015-05-21T07:22:20.230 回答