-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathdemo6.html
More file actions
81 lines (69 loc) · 2 KB
/
demo6.html
File metadata and controls
81 lines (69 loc) · 2 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
73
74
75
76
77
78
79
80
81
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>$.ajax文件分块上传,和断点续传</title>
</head>
<body>
<p>在 demo5.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
$('#file').change(function() {
var files = this.files
var file = files[0]
// 在 demo5.html 的基础上改为,先向服务端查询待上传文件的断点处位置,以实现断点续传。
var url = 'filesize.php?filename=' + encodeURIComponent(file.name)
$.get(url, function(json) {
// 服务端返回的开始位置
start = json.data[file.name.replace(/\.\w+$/, '')]
console.log(['start', start])
upload(file)
}, 'json')
})
function upload(file) {
var data = new FormData()
data.append("name", encodeURIComponent(file.name))
data.append("file", file.slice(start, start + preUploadSize))
data.append("start", start)
$.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) {
document.title = e.loaded
}
return xhr
}
}).then(function() {
start += preUploadSize
if (start < file.size) {
// 进行下一段上传
// 为了演示,每次延时3秒钟
setTimeout(function(){upload(file)}, 3000)
} else {
alert('上传结束')
}
}, function() {
alert('上传错误')
})
}
}(jQuery)
</script>
</body>
</html>