Javascript 在上传之前验证 AngularJs 中的文件扩展名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29778809/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:58:00  来源:igfitidea点击:

Validating file extension in AngularJs before uploading

javascriptangularjsfrontendimage-uploading

提问by Ali Saberi

I am uploading images for our application to the server. Is there any way to validate the extensions in client side by JS before submitting them to the server before uploading them to server?

我正在将我们的应用程序的图像上传到服务器。在将它们上传到服务器之前,有没有办法在将它们提交到服务器之前通过 JS 验证客户端中的扩展?

I am using AngularJs to handle my front-end.

我正在使用 AngularJs 来处理我的前端。

回答by Sanjeev Singh

You can use this simple javascript to validate. This code should be put inside a directive and on change of file upload control.

您可以使用这个简单的 javascript 进行验证。此代码应放在指令中并用于更改文件上传控制。

var extn = filename.split(".").pop();

Alternatively you can use javascript substring method also:

或者,您也可以使用 javascript 子字符串方法:

fileName.substr(fileName.lastIndexOf('.')+1)

回答by ecarrizo

You can create a angular directive, something like this should work (Change the accepted values in the validFormats array);

您可以创建一个角度指令,这样的东西应该可以工作(更改 validFormats 数组中的接受值);

HTML:

HTML:

    <form name='fileForm' >
        <input type="file" name="file" ng-model="fileForm.file" validfile>
    </form>

Javascript:

Javascript:

angular.module('appname').directive('validfile', function validFile() {

    var validFormats = ['jpg', 'gif'];
    return {
        require: 'ngModel',
        link: function (scope, elem, attrs, ctrl) {
            ctrl.$validators.validFile = function() {
                elem.on('change', function () {
                   var value = elem.val(),
                       ext = value.substring(value.lastIndexOf('.') + 1).toLowerCase();   

                   return validFormats.indexOf(ext) !== -1;
                });
           };
        }
    };
});

回答by Aniket Muruskar

for file validation i.e required,file extension,size.Create custom directive and used angular js ng-message module for simplify the validation errors

用于文件验证,即必需文件扩展名大小。创建自定义指令并使用 angular js ng-message 模块来简化验证错误

HTML

HTML

<input type="file" ng-model="imageFile" name="imageFile" valid-file required>

<div ng-messages="{FORMNAME}.imageFile.$error" ng-if="{FORMNAME}.imageFile.$touched">
     <p ng-message="required">This field is required</p>
     <p ng-message="extension">Invalid Image</p>
 </div>

Angular JS

角JS

customApp.directive('validFile', function () {
return {
    require: 'ngModel',
    link: function (scope, elem, attrs, ngModel) {
        var validFormats = ['jpg','jpeg','png'];
        elem.bind('change', function () {
            validImage(false);
            scope.$apply(function () {
                ngModel.$render();
            });
        });
        ngModel.$render = function () {
            ngModel.$setViewValue(elem.val());
        };
        function validImage(bool) {
            ngModel.$setValidity('extension', bool);
        }
        ngModel.$parsers.push(function(value) {
            var ext = value.substr(value.lastIndexOf('.')+1);
            if(ext=='') return;
            if(validFormats.indexOf(ext) == -1){
                return value;
            }
            validImage(true);
            return value;
        });
    }
  };
});

Requireangular-messages.min.js

需要angular-messages.min.js

回答by Shakeer Hussain

Here is the complete code for validating file extension usign AngularJs

这是验证文件扩展名使用 AngularJs 的完整代码

<!DOCTYPE html>
<html>
<head>
    <title></title>

    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>

    <script type='text/javascript'>
            var myApp = angular.module('myApp', []);
            myApp.controller('MyCtrl', function($scope) {
                $scope.setFile = function(element) {
                    $scope.$apply(function($scope) {
                        $scope.theFile = element.files[0];
                        $scope.FileMessage = '';
                        var filename = $scope.theFile.name;
                        console.log(filename.length)
                        var index = filename.lastIndexOf(".");
                        var strsubstring = filename.substring(index, filename.length);
                        if (strsubstring == '.pdf' || strsubstring == '.doc' || strsubstring == '.xls' || strsubstring == '.png' || strsubstring == '.jpeg' || strsubstring == '.png' || strsubstring == '.gif')
                        {
                          console.log('File Uploaded sucessfully');
                        }
                        else {
                            $scope.theFile = '';
                              $scope.FileMessage = 'please upload correct File Name, File extension should be .pdf, .doc or .xls';
                        }

                    });
                };
            });
    </script>

</head>
<body ng-app="myApp">
    <div ng-controller="MyCtrl">
        <input type="file"
               onchange="angular.element(this).scope().setFile(this)">
        {{theFile.name}}
        {{FileMessage}}
    </div>

</body>
</html>

回答by Matias Fernandez Martinez

You can add a custom directive which checks for the element.filesarray in order to check the type on the onchangeevent. There is no embedded validation for file input.

您可以添加一个自定义指令来检查element.files数组以检查onchange事件的类型。没有针对文件输入的嵌入式验证。

回答by jcc

File Upload using AngularJS

使用 AngularJS 上传文件

There are many modules that can help you with this. Any one of these should allow you to define a filter to only upload certain file extensions.

有许多模块可以帮助您解决这个问题。其中任何一个都应该允许您定义过滤器以仅上传某些文件扩展名。

If you're looking for a simpler solution, you can use something like string.jsto ensure the filenames of the files being uploaded are of extension '.png'.

如果您正在寻找更简单的解决方案,您可以使用string.js 之类的东西来确保上传的文件的文件名扩展名为“.png”。