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

	var imgTmp = ""



//    1. 页面把组件的内容添加进去
    self.initView = function(){
        file =  root.find(".uploadFile");
        file.live("change", function(){
            //校验
			if(!$(this).attr("name")){
				$(this).attr("name","image")	
			}
            if(self.validate($(this).val())){
				
                //self.showImg();
                //self.fetchImg().attr("src", cfg.loading);
                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) {
                //console.log(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;
        for(var extension in cfg.extensionArr){
            if(cfg.extensionArr[extension] == fileExtension){
                return true;
            }
        }
        if(!flag){
			Alert("请上传图片格式("+cfg.extensionArr+")");	
		}
    }


    self.initView();
}

var img_config = {
    url : "http://user.nong12.com/common/upload_image.do",
    extensionArr : [".jpg",".gif",".jpeg",".bmp",".png"],
    loading: "http://static.nong12.com/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);
}