文件类型校验

<!doctype html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <meta name="Generator" content="EditPlus®">
        <meta name="Author" content="hapday">
        <meta name="Keywords" content="类型校验" />
        <meta name="Description" content="类型校验" />
        <title>格式校验</title>
        <script type="text/javascript">
            /**
             * 类型校验
             * @param types 类型标准,(英文状态下)逗号分隔
             * @param fileName 文件名
             * @return 合法返回 true,否则返回 false
            */
            var typeVerify = function(types, fileName) {
                if(undefined === fileName || null === fileName || '' === fileName) {
                    return false;
                }

                if(undefined === types || null === types || '' === types) {
                    types = 'jpg, png, gif, txt, xls';
                }

                var lastDotIndex = fileName.lastIndexOf('.');
                if(-1 === lastDotIndex) {
                    return false;
                }
                
                var expandedName = fileName.substring(lastDotIndex + 1, fileName.length).toLowerCase();
                var types_ = types.split(',');

                for(var index = 0; index < types_.length; index++) {
                    var standard = types_[index].trim();
                    if(standard === expandedName) {
                        return true;
                    }
                }

                return false;
            }

            var materialUpload = function(){
                var materialFile = window.document.getElementById('materialFile');
                alert(typeVerify('jpg, png, tif', materialFile.value));
            }
        </script>
    </head>
    <body>
        <input type="file" id="materialFile" />
        <input type="button" value="上传" onclick="materialUpload();" />
    </body>
</html>

 

原文地址:https://www.cnblogs.com/hapday/p/6843987.html