js限制上传文件类型和大小

<html>    
<head>    

<script type="text/javascript">    

function fileChange(target){  
//检测上传文件的类型 
var imgName = document.all.up_file.value;
     var ext,idx;   
    if (imgName == ''){  
       document.all.submit_upload.disabled=true; 
        alert("请选择需要上传的文件!");  
        return; 
    } else {   
        idx = imgName.lastIndexOf(".");   
        if (idx != -1){   
            ext = imgName.substr(idx+1).toUpperCase();   
            ext = ext.toLowerCase( ); 
           // alert("ext="+ext);
            if (ext != 'jpg' && ext != 'png' && ext != 'jpeg' && ext != 'gif'){
              document.all.submit_upload.disabled=true;   
                alert("只能上传.jpg  .png  .jpeg  .gif类型的文件!"); 
                return;  
            }   
        } else {  
          document.all.submit_upload.disabled=true; 
           alert("只能上传.jpg  .png  .jpeg  .gif类型的文件!"); 
            return;
        }   
    }
    
    //检测上传文件的大小        
    var isIE = /msie/i.test(navigator.userAgent) && !window.opera;  
    var fileSize = 0;           
    if (isIE && !target.files){       
        var filePath = target.value;       
        var fileSystem = new ActiveXObject("Scripting.FileSystemObject");          
        var file = fileSystem.GetFile (filePath);       
        fileSize = file.Size;      
    } else {      
        fileSize = target.files[0].size;       
    }     

    var size = fileSize / 1024*1024;   

    if(size>(1024*200)){    
    document.all.submit_upload.disabled=true;
        alert("文件大小不能超过200KB");   
    }else{
    document.all.submit_upload.disabled=false;
    }    
}     
</script>    
</head>    
<body>    
<input type="file" id="up_file" name="up_file" onchange="fileChange(this);" />                   
<input id="submit_upload" type="submit" class="load-btn" value="上传" disabled />   
</body>    
</html> 

 

posted @ 2016-05-11 16:44  dreamflower  阅读(18781)  评论(0编辑  收藏  举报