0

Anyone know how to check a file extension on a file input and display a div based on the file type. I need to give different upload option based on the file being uploaded. It text asks for an input type or zip shows an alternative division.

Si Smith
  • 1
  • 1
  • 2

1 Answers1

0

Using this answer from another question, watch for changes on the file input. Get the type of the file, add it to scope and then use ng-show/ng-if to show/hide the correct element(s).

var app = angular.module("app", []);

app.controller("controller", function($scope) {
  $scope.file = {};
  $scope.fileType = "";
  
  $scope.uploadFile = function() {
    $scope.fileType = $scope.file.name.substring($scope.file.name.lastIndexOf(".") + 1);
  };
});

// See https://stackoverflow.com/a/24085688/3894163
app.directive('file', function() {
    return {
        require:"ngModel",
        restrict: 'A',
        link: function($scope, el, attrs, ngModel){
            el.bind('change', function(event){
                var files = event.target.files;
                var file = files[0];

                ngModel.$setViewValue(file);
                $scope.$apply();
            });
        }
    };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>

<div ng-app="app" ng-controller="controller">

  <input data-file ng-model="file" type="file" ng-change="uploadFile()" />
  
  File type: {{fileType}}
  
  <div ng-show="fileType === 'txt'">
    TXT
  </div>

  <div ng-show="fileType === 'pdf'">
    PDF
  </div>

  <div ng-show="fileType === 'png'">
    PNG
  </div>
  
  <div ng-show="fileType === 'jpg'">
    JPG
  </div>
  
  <div ng-show="fileType === 'docx'">
    DOCX
  </div>
  
</div>
Community
  • 1
  • 1
Jaydo
  • 1,830
  • 2
  • 16
  • 21