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.

1
  • you mean other than the files array of the input[type="file"]?? Commented Apr 17, 2016 at 23:47

1 Answer 1

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.