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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
<form method="POST" enctype="multipart/form-data">
上传文件:
<input
multiple
id="file"
type="file"
name="file"
placeholder="上传文件"
/>
<button id="upload" type="button">上传</button>
</form>
<script>
$("#upload").click(() => {
getUploadId();
//upload();
});
</script>
<script>
function getUploadId() {
let file = document.getElementById("file").files[0];
$.ajax({
url: "/test/api/file/get-uploadId?fileName="+file.name,
type: "post",
processData: false,
contentType: false,
}).success((res)=>{
console.log(res);
let uploadId = res.data.uploadId;
console.log('uploadId',uploadId);
//
upload(uploadId)
})
}
</script>
<script>
//设置每个切片大小 , 2M
let bytesPerPiece = 1024 * 1024 * 2;
//上传文件函数
function upload(uploadId) {
//获取上传文件
let file = document.getElementById("file").files[0];
console.log(file);
let start = 0,
end,
index = 0,
filesize = file.size,
name = file.name;
//计算切片总数
let totalPieces = Math.ceil(filesize / bytesPerPiece);
console.log('total pieces = ',totalPieces)
let ucnt = 0; //用于记录第几个数据包
while (ucnt < totalPieces) {
end = start + bytesPerPiece;
if (end > filesize) {
end = filesize;
}
let chunk = file.slice(start, end);
let formData = new FormData();
ucnt++;
let filename = `${name}-no-${ucnt}`;
formData.append('uploadId',uploadId);
formData.append("file", chunk, filename);
//seq 表示 第几个数据包
formData.append("seq", ucnt);
//提交总分片数量
formData.append("total",totalPieces);
//最终名字
formData.append("targetName",name);
//原生js发请求
// let xhr = new XMLHttpRequest();
// xhr.onreadystatechange = function(){
// if(this.readyState == 4 && this.status == 200){
// }
// }
// xhr.open('post', '/api/upload', true);
// xhr.send(formData);
// 使用jquery,需要将contentType,processData设置为false
console.log("upload --", formData, ucnt);
$.ajax({
url: "/test/api/file/oss-slice",
type: "post",
data: formData,
processData: false,
contentType: false,
async: false,
})
.success((res) => {
console.log("ok .. {}", res);
})
.error((err) => {});
//传输下一部分
start = end + 1
}
}
</script>
</body>
</html>
|