-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathupload.js
77 lines (56 loc) · 1.92 KB
/
upload.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
var handleUpload = function(event){
event.preventDefault();
event.stopPropagation();
var fileInput = document.getElementById('file');
var data = new FormData();
data.append('ajax', true);
for (var i = 0; i < fileInput.files.length; i++) {
data.append('file[]', fileInput.files[i]);
};
var request = new XMLHttpRequest();
request.upload.addEventListener('progress', function(event){
if (event.lengthComputable) {
var percent = event.loaded / event.total;
var progress = document.getElementById('upload_progress');
while (progress.hasChildNodes()){
progress.removeChild(progress.firstChild);
}
progress.appendChild(document.createTextNode(Math.round(percent * 100) + ' %'));
};
});
request.upload.addEventListener('load', function(event){
document.getElementById('upload_progress').style.display = "none";
});
request.upload.addEventListener('error', function(event){
alert('Upload failed');
});
request.addEventListener('readystatechange', function(event){
if (this.readyState == 4){
if (this.status == 200){
var links = document.getElementById('uploaded');
console.log(this.response);
var uploaded = eval(this.response);
var div, a;
for (var i = 0; i < uploaded.length; i++) {
div = document.createElement('div');
a = document.createElement('a');
a.setAttribute('href', 'files/' + uploaded[i]);
a.appendChild(document.createTextNode(uploaded[i]));
div.appendChild(a);
links.appendChild(div);
};
}else{
console.log('Server replied with HTTP status' + this.status);
}
}
})
request.open('POST', 'upload.php');
request.setRequestHeader('Cache-Control', 'no-cache');
document.getElementById('upload_progress').style.display = "block";
request.send(data);
}
window.addEventListener('load', function(event){
if (FormData);
var submit = document.getElementById('submit');
submit.addEventListener('click', handleUpload);
});