-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathdemo5.html
More file actions
72 lines (62 loc) · 1.59 KB
/
demo5.html
File metadata and controls
72 lines (62 loc) · 1.59 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
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>$.ajax文件分块上传</title>
</head>
<body>
<p>在 demo4.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
$('#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))
$.ajax({
type: 'POST',
url: 'upload.php',
data: data,
// 设置 false 以使用文件上传的 Content-Type
// 如 Content-Type:multipart/form-data; boundary=----WebKitFormBoundarykdtBZ0dnFQOWcXu3
contentType: false,
// 避开jQuery对 data 对象的默认处理
processData: false,
// 设置 xhr 对象,增加 onprogress 事件
xhr: function() {
var xhr = $.ajaxSettings.xhr();
xhr.upload.onprogress = function(e) {
total += e.loaded
document.title = '上传 ' + total + ' 字节'
}
return xhr
}
}).then(function() {
start += preUploadSize
if (start < file.size) {
// 在 demo4.html 的基础上改为,可以分块连续上传整个文件。
upload(file)
} else {
alert('上传结束')
}
}, function() {
alert('上传错误')
})
}
}(jQuery)
</script>
</body>
</html>