-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathspliceUpload.js
92 lines (70 loc) · 2.04 KB
/
spliceUpload.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
function initUpload(){
var chunk = 100 * 1024
var input = document.querySelector('#file')
input.onchange = function(e){
var file = this.files[0];
var query = {}
var chunks = [];
if(!!file){
var start = 0;
for(var i = 0; i < Math.ceil(file.size / chunk);i++){
var end = start + chunk;
chunks[i] = file.slice(start,end)
start = end
}
query = {
fileSize:file.size,
dataSize:chunk,
nextOffset:0
}
upload(chunks,query,successPerUpload)
}
}
}
function upload(chunks,query,cb){
var queryStr = Object.keys(query).map(key =>{
return key + '=' + query[key]
}).join('&')
var xhr = new XMLHttpRequest()
xhr.open('POST','http://xxx/upload?' + queryStr);
xhr.overrideMimeType('application/octet-stream')
var index = Math.floor(query.nextOffset / query.dataSize)
getFileBinary(chunks[index],function(binary){
if(xhr.sendAsBinary){
xhr.sendAsBinary(binary)
}else{
xhr.send(binary)
}
})
xhr.onreadystatechange = function(e){
if(xhr.readyState === 4){
if(xhr.status === 200){
var resp = JSON.parse(xhr.responseText)
//resp = {
// isFinish:false,
// offset:100 * 1024
// }
if(typeof cb === 'function'){
cb.call(this,resp,chunks,query)
}
}
}
}
}
function successPerUpload(resp,chunks,query){
if(resp.isFinish === true){
alert("上传成功")
}else{
query.offset = resp.offset
upload(chunks,query,successPerUpload)
}
}
function getFileBinary(file,cb){
var reader = new FileReader()
reader.readAsArrayBuffer(file);
reader.onload = function(e){
if(typeof cb === "function"){
cb.call(this,this.result)
}
}
}