-
Notifications
You must be signed in to change notification settings - Fork 8
/
uploader.js
94 lines (84 loc) · 2.6 KB
/
uploader.js
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
function uploader(input, options) {
var $this = this;
// Default settings (mostly debug functions)
this.settings = {
prefix:'file',
multiple:false,
autoUpload:false,
url:window.location.href,
onprogress:function(ev){ console.log('onprogress'); console.log(ev); },
error:function(msg){ console.log('error'); console.log(msg); },
success:function(data){ console.log('success'); console.log(data); }
};
$.extend(this.settings, options);
this.input = input;
this.xhr = new XMLHttpRequest();
this.send = function(){
// Make sure there is at least one file selected
if($this.input.files.length < 1) {
if($this.settings.error) $this.settings.error('Must select a file to upload');
return false;
}
// Don't allow multiple file uploads if not specified
if($this.settings.multiple === false && $this.input.files.length > 1) {
if($this.settings.error) $this.settings.error('Can only upload one file at a time');
return false;
}
// Must determine whether to send one or all of the selected files
if($this.settings.multiple) {
$this.multiSend($this.input.files);
}
else {
$this.singleSend($this.input.files[0]);
}
};
// Prep a single file for upload
this.singleSend = function(file){
var data = new FormData();
data.append(String($this.settings.prefix),file);
$this.upload(data);
};
// Prepare all of the input files for upload
this.multiSend = function(files){
var data = new FormData();
for(var i = 0; i < files.length; i++) data.append(String($this.settings.prefix)+String(i), files[i]);
$this.upload(data);
};
// The actual upload calls
this.upload = function(data){
$this.xhr.open('POST',$this.settings.url, true);
$this.xhr.send(data);
};
// Modify options after instantiation
this.setOpt = function(opt, val){
$this.settings[opt] = val;
return $this;
};
this.getOpt = function(opt){
return $this.settings[opt];
};
// Set the input element after instantiation
this.setInput = function(elem){
$this.input = elem;
return $this;
};
this.getInput = function(){
return $this.input;
};
// Basic setup for the XHR stuff
if(this.settings.onprogress) this.xhr.upload.addEventListener('progress',this.settings.onprogress,false);
this.xhr.onreadystatechange = function(ev){
if($this.xhr.readyState == 4) {
console.log('done!');
if($this.xhr.status == 200) {
if($this.settings.success) $this.settings.success($this.xhr.responseText,ev);
$this.input.value = '';
}
else {
if($this.settings.error) $this.settings.error(ev);
}
}
};
// onChange event for autoUploads
if(this.settings.autoUpload) this.input.onchange = this.send;
}