zoukankan      html  css  js  c++  java
  • 限制上传文件的类型

    h5方式

    accept 属性只能与 <input type="file"> 配合使用。它规定能够通过文件上传进行提交的文件类型

    demo:

    <form>
      <input type="file" name="pic" id="pic" accept="image/gif, image/jpeg" />
    </form>
     
    <!-- 如果不限制图像的格式,可以写为:accept="image/*"。 -->
    

    js方式

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
    </head>
    <body>
    <input type="file" name="contractFileName" style=" 500px;" onchange="fileChange(this);"/>
    
    <script type="text/javascript">
        var isIE = /msie/i.test(navigator.userAgent) && !window.opera;
        function fileChange(target,id) {
            var fileSize = 0;
            var filetypes =[".jpg",".png",".rar",".txt",".zip",".doc",".ppt",".xls",".pdf",".docx",".xlsx"];
            var filepath = target.value;
            var filemaxsize = 1024*2;//2M
            if(filepath){
                var isnext = false;
                var fileend = filepath.substring(filepath.lastIndexOf("."));
                if(filetypes && filetypes.length>0){
                    for(var i =0; i<filetypes.length;i++){
                        if(filetypes[i]==fileend){
                            isnext = true;
                            break;
                        }
                    }
                }
                if(!isnext){
                    alert("不接受此文件类型!");
                    target.value ="";
                    return false;
                }
            }else{
                return false;
            }
            if (isIE && !target.files) {
                var filePath = target.value;
                var fileSystem = new ActiveXObject("Scripting.FileSystemObject");
                if(!fileSystem.FileExists(filePath)){
                    alert("附件不存在,请重新输入!");
                    return false;
                }
                var file = fileSystem.GetFile (filePath);
                fileSize = file.Size;
            } else {
                fileSize = target.files[0].size;
            }
    
            var size = fileSize / 1024;
            if(size>filemaxsize){
                alert("附件大小不能大于"+filemaxsize/1024+"M!");
                target.value ="";
                return false;
            }
            if(size<=0){
                alert("附件大小不能为0M!");
                target.value ="";
                return false;
            }
        }
    </script>
    
    </body>
    </html>
    
  • 相关阅读:
    [LeetCode#68] Text Justification
    [LeetCode#227] Basic Calculator II
    [LeetCode#87] Scramble String
    [LeetCode#280] Wiggle Sort
    [LeetCode#272] Closest Binary Search Tree Value II
    [LeetCode#254] Factor Combinations
    [LeetCode#174] Dungeon Game
    python报错集合
    在线画图工具
    xml模块(了解)
  • 原文地址:https://www.cnblogs.com/lyly96720/p/12107497.html
Copyright © 2011-2022 走看看