利用js的对象特性做文件上传验证(图片版)

有码有真相:先上代码 imgValOptions.js


// JavaScript Document
//文件验证的配置文件,暂时做了图片的上传验证,支持gif/png/jpg/bmp等文件的上传,可更改类型和配置项
var imgValOptions = {
gif : 1,
png : 1,
jpg : 1,
bmp : 1,
rar : 0,
zip : 0,
swf : 0
};



上示代码为文件上传的配置文件,可根据自己的需求添加,1默认为true,0默认为false。


控制类的代码如下:imgVal.js

// JavaScript Document
//提供图片验证的数组
var imgValidateCons = {};

/*
imgValidateCons.store存储上传验证的配置值
init()
*检测imgValOptions是否存在,如果存在则将其中所有的配置项以及值写在imgValidateCons.store中
imgValidateCons.store.add(cons, b)
*cons:配置项
*b:配置值
*将配置项和值存储在imgValidateCons.store对象中
imgValidateCons.store.check(cons)
*cons:配置项
*验证配置项是否存在或者是否值为1
*/
imgValidateCons.store = {
init : function(){
if(imgValOptions) {
for(var con in imgValOptions)
{
imgValidateCons.store[con] = imgValOptions[con];
}
}
},
add : function(cons, b){imgValidateCons.store[cons] = b; return 1;},
check : function(cons){
var store = imgValidateCons.store;
if(store[cons])
return 1;
else
return 0;
}
}

imgValidateCons.store.init()负责初始化,如有options在imgValOptions.js中,则读入配置项,完成初始化,add负责添加新的配置项,check负责检验。
最后给出一个例子,其中的store.check(cons)可以被store[cons]替代,这是访问对象属性的一种方法。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>图片上传验证</title>
</head>

<body>
<form action="www.baidu.com" method="post" id="form">
<input type="file" id="file" name="file" />
<input type="button" οnclick="submitBefore()"/>
</form>
</body>
<script type="text/javascript" src="imgValOptions.js"></script>
<script type="text/javascript" src="imgVal.js"></script>
<script type="text/javascript">
var store = "";
var d = document;

window.onload = function(){
imgValidateCons.store.init();
store = imgValidateCons.store;
};

var submitBefore = function(){
var file = d.getElementById("file");
fileVal = file.value;
fileSuffix = fileVal.substr(fileVal.lastIndexOf(".") + 1, fileVal.length);
if(store.check(fileSuffix)) d.getElementById("form").submit();
//if(store.check[fileSuffix]) d.getElementById("form").submit();
return false;
};
</script>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值