ITeye博客

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

stargaga · 2011-06-11 18:19 · javascript技术 · Web前端 · Markdown

有码有真相:先上代码 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 = imgValOptions; } } }, add : function(cons, b){imgValidateCons.store = b; return 1;}, check : function(cons){ var store = imgValidateCons.store; if(store) return 1; else return 0; } }

imgValidateCons.store.init()负责初始化,如有options在imgValOptions.js中,则读入配置项,完成初始化,add负责添加新的配置项,check负责检验。
最后给出一个例子,其中的store.check(cons)可以被store替代,这是访问对象属性的一种方法。

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) d.getElementById("form").submit(); return false; };

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。