当前位置:编程学习 > JS >>

JS中INPUT上传文件类型限制代码

在客户端进行验证
 

 代码如下 复制代码
<script   Language="JavaScript"   Type="text/javascript"> <!--
function   picForm_Validator(myform)
{
if(document.all.file1.value=="")
        {
                alert("请选择上传的照片!");
                myform.mfile.focus();
                return   false;
        }
        var   last=document.all.file1.value.match(/^(.*)(.)(.{1,8})$/)[3];   //检查上传文件格式
        last=last.toUpperCase();
        if(last=="GIF"   ||   last=="JPG"){ 
        }
        else
        {
                alert("只能上传.GIF   或.JPG   文件,请重新选择!");
                return   false;
                }
        return   true;
}
//-->
</script>
<form  method="POST" enctype="multipart/form-data"   action="xx.action"   onsubmit="return   picForm_Validator(this)">
<input   name="file1"   type="file"   class="style4"   value=""   size="40">
<input   type="submit"   value="上传"   name="B1"   class="s02">
</form>

例2

 代码如下 复制代码

<SCRIPT language="JavaScript">

<!-- Hide script from older browsers

 

extArray = new Array(".gif", ".jpg", ".png");

 

function LimitAttach(form, file) {

allowSubmit = false;

if (!file) return;

while (file.indexOf("\") != -1)

file = file.slice(file.indexOf("\") + 1);

ext = file.slice(file.indexOf(".")).toLowerCase();

for (var i = 0; i < extArray.length; i++) {

if (extArray[i] == ext) { allowSubmit = true; break; }

}

if (allowSubmit) form.submit();

else

alert("Please only upload files that end in types:  "

+ (extArray.join("  ")) + "nPlease select a new "

+ "file to upload and submit again.");

}

//  End -->

</script>

<form method="POST" action="newphoto.asp" enctype="multipart/form-data" id=form1 name=form1>

<input type="file" name="UploadForm" size="30"><BR><BR>

<input type="button" name="submit" value="Upload Your Photo!" onclick="LimitAttach(this.form, this.form.UploadForm.value)">

 

———————————————————

<form onsubmit= "return a(this) ">

<input type=file name=f>

<input type=submit>

</form>

例3

原理简单就是获取上传文件的字符,然后正则表达式判断是不是指定文件。

 代码如下 复制代码

<input type="file" onchange="checkExt(this)"/>

<script >
var checkExt=function(file) {
    if(!(/(?:jpg|gif)$/i.test(file.value))) {
        alert("只允许上传jpg和gif的图片");
        if(window.ActiveXObject) {//for IE
            file.select();//select the file ,and clear selection
            document.selection.clear();
        } else if(window.opera) {//for opera
            file.type="text";file.type="file";
        } else file.value="";//for FF,Chrome,Safari
    } else {
        alert("ok");//or you can do nothing here.
    }
};
</script>

个人比较喜欢最后一种,他可以判断浏览器类哦,兼容性也相对强不少了

补充:网页制作,js教程 
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,