uploadImg.js
2.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
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);
}