-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathdemo3.html
More file actions
63 lines (57 loc) · 1.28 KB
/
demo3.html
File metadata and controls
63 lines (57 loc) · 1.28 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
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Ajax文件分块上传</title>
</head>
<body>
<p>在 demo2.html 的基础上增加一次上传成功的回调方法。</p>
<form action="upload.php">
<input type="file" id="file">
</form>
<script src="jquery-1.11.0.js"></script>
<script>
~function($){
// 每次上传文件的一段,单位:字节
var preUploadSize = 1024 * 2
var start = 0
var xhr = new XMLHttpRequest()
var total = 0
xhr.upload.onprogress = function(e) {
total += e.loaded
document.title = '上传 ' + total + ' 字节'
}
$('#file').change(function() {
var files = this.files
var file = files[0]
upload(file)
})
function upload(file) {
var data = new FormData()
data.append("name", encodeURIComponent(file.name))
data.append("file", file.slice(start, start + preUploadSize))
xhr.open("post", 'upload.php')
// 在 demo2.html 的基础上增加一次上传成功的回调方法
xhr.onreadystatechange = function(e) {
var json
if (xhr.readyState == 4) {
if (xhr.status == 200) {
try {
json = JSON.parse(xhr.responseText)
if (json && json.succ) {
alert('一次上传结束')
}
} catch (e) {
alert('上传错误')
}
} else {
alert('上传错误')
}
}
}
xhr.send(data)
}
}(jQuery)
</script>
</body>
</html>