uploadImg.js 2.47 KB
function UploadImg(cfg){
    var cfg = cfg;
    var self = this;
    var root = $(cfg.root);
    var file, currentImg;

	var imgTmp = ""



//    1. 页面把组件的内容添加进去
    self.initView = function(){
        file =  root.find(".uploadFile") || root.find(".upload-file");
        file.live("change", function(e){
            //校验
            if(self.validate($(this).val())){
                //self.showImg();
                //self.fetchImg().attr("src", cfg.loading);
            	var id = $(this).attr("id");
            	if(id){
            		if(id.indexOf("jUploadFile")==-1){
            			self.upload($(this).val(), $(this));
            		}
            	}else{
            		self.upload($(this).val(), $(this));
            	}
            }
//            DlFileUpLoad.run($(this).val(),$(this).attr("id"));
        });

    };
//    2. 实现上传功能
    self.upload = function (val,obj){
        $.ajaxFileUpload({
            url: cfg.url,
            secureuri: false,
            fileElementId: obj,
            dataType: 'json',
            success: function (data) {
                cfg.success(data);
            },
            error: function (data) {
				cfg.error(data);
            }
        });
    }


    /**
     * 添加图片到页面
     * @param src
     */
    self.showImg = function(src){
        currentImg = $(imgTmp);
        currentImg.attr("src", src);
    };
    /**
     * 获取当前图片(默认最后一个)
     * @returns {*}
     */
    self.fetchImg = function(){
        return currentImg;
    }
//    3. 相关的配置, 以及设置, 过滤
    self.validate = function(path){
        var fileExtension = /\.[^\.]+$/.exec(path);
        var flag = false;
        if(fileExtension && fileExtension.length > 0){
	        for(var extension in cfg.extensionArr){
	            if(cfg.extensionArr[extension] == fileExtension[0].toLowerCase()){
	                return true;
	            }
	        }
        }
        if(!flag){
			Alert("请上传图片格式("+cfg.extensionArr+")");	
		}
    }


    self.initView();
}

var img_config = {
    url : window.DiliPath.userPath+"/common/upload_image.do",
    extensionArr : [".jpg",".gif",".jpeg",".bmp",".png"],
    loading: window.DiliPath.staticPath+"/static/common/images/i/dili_download108.gif",
	success:function(data){},
	error:function(data){}
};

$.fn.uploadImg = function(cfg){
    var box = $(this);
    cfg.root = box;
    var c = $.extend(true, {}, img_config, cfg);
    var img = new UploadImg(c);
}