-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathdemo4.html
More file actions
64 lines (55 loc) · 1.41 KB
/
demo4.html
File metadata and controls
64 lines (55 loc) · 1.41 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
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Ajax文件分块上传,使用jQuery.ajax()方法</title>
</head>
<body>
<p>在 demo3.html 的基础上改为使用 $.ajax 方法</p>
<form action="upload.php">
<input type="file" id="file">
</form>
<script src="jquery-1.11.0.js"></script>
<script>
~function($){
// 每次上传文件的一段,单位:字节
var preUploadSize = 2 * 2
var start = 0
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))
// 在 demo3.html 的基础上改为使用 $.ajax 方法
$.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: function() {
var xhr = $.ajaxSettings.xhr();
xhr.upload.onprogress = function(e) {
total += e.loaded
document.title = '上传 ' + total + ' 字节'
}
return xhr
}
}).then(function(){
alert('一次上传成功')
}, function(){
alert('上传错误')
})
}
}(jQuery)
</script>
</body>
</html>