-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmyajaxfiled.js
More file actions
107 lines (88 loc) · 2.48 KB
/
myajaxfiled.js
File metadata and controls
107 lines (88 loc) · 2.48 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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
function upload(url,inputObj,progressObj,imgObj){
var inputObj=inputObj||{};
if(inputObj.nodeName=="INPUT"){
this.inputObj=inputObj;
}else if(typeof inputObj=="string"){
this.inputObj=document.querySelector(inputObj);
}
var progressObj=progressObj||{};
if(progressObj.nodeName=="DIV"){
this.progressObj=progressObj;
}else if(typeof progressObj=="string"){
this.progressObj=document.querySelector(progressObj);
}
var imgObj=imgObj||{};
if(imgObj.nodeName=="IMG"){
this.imgObj=imgObj;
}else if(typeof imgObj=="string"){
this.imgObj=document.querySelector(imgObj);
}
this.type=["jpeg","jpg","png","gif"];
this.size=1024*1024*20;
this.uploadName="file";
this.url=url;
}
upload.prototype={
up:function(callback){
if(this.url){
this.callback=callback;
this.getCon();
}else{
alert("请指定路径");
}
},
getCon:function(){
var that=this;
this.inputObj.onchange=function(){
that.data=this.files[0];
var read=new FileReader();
read.onload=function(e){
that.imgObj.src=e.target.result;
}
read.readAsDataURL(that.data);
if(that.check()){
that.upfile();
}
}
},
check:function(){
var that=this;
console.log(that.data);
var data=that.data;
var size=data.size;
var extname=data.name.substr(data.name.lastIndexOf(".")+1).toLowerCase();
if(size>that.size){
alert("文件太大");
return false;
}
var flag=false;
for(var i=0;i<that.type.length;i++){
if(that.type[i]==extname){
flag=true;
break;
}
}
if(!flag){
alert("格式不符")
return false
}
return true;
},
upfile:function(){
var that=this;
var ajax=new XMLHttpRequest();
var form=new FormData();
form.append(this.uploadName,this.data);
ajax.upload.onprogress=function(e){
var total=e.total;
var loaded=e.loaded;
var scale=loaded/total*100;
that.progressObj.style.width=scale+"%";
}
ajax.onload=function(){
that.callback(ajax.response);
}
ajax.open("post",that.url);
ajax.send(form);
}
}