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.
Asked
Active
Viewed 2,604 times
0
-
you mean other than the files array of the input[type="file"]?? – Dayan Moreno Leon Apr 17 '16 at 23:47
1 Answers
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>