-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
175 lines (161 loc) · 4.83 KB
/
index.html
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>超大文件下载HTTP range方案</title>
</head>
<body>
<button class="download">下载超大文件</button>
<script src="https://cdn.jsdelivr.net/npm/streamsaver@2.0.6/StreamSaver.min.js"></script>
<script>
class OversizeFileDownloader {
url;
limitSize;
processHandler; // 进度钩子
// 下面数据结束后需要重置
isDownload = false; // 是否正在下载
fileTotalSize = 0; // 总二进制大小(字节)
filename = ""; // 文件名
bufferPos = 0; // 已下载字节大小
processLastTime = 0; // 进度钩子最后一次执行的时间
downloadFilename;
constructor(options) {
const { url, processHandler, limitSize = 1024 * 1024 * 1024, downloadFilename } = options;
if (!url) {
throw TypeError("url is must");
}
this.url = url;
this.limitSize = limitSize; // 默认1G
this.downloadFilename = downloadFilename || Date.now().toString();
if (!processHandler) {
this.processHandler = function() {
console.log("progress", (this.bufferPos / this.fileTotalSize * 100).toFixed(2) + "%");
};
} else {
this.processHandler = processHandler;
}
}
/**
* 静态资源下载启动器
*/
async downloadAssetsStater() {
if (this.isDownload) {
console.warn("downloader is running, pls wait 'isDownload = false'");
return;
}
this.isDownload = true;
this.fileTotalSize = await this.getAssetsSize(); // 静态资源总大小
const res = await this.downloadAssetFile();
await this.pipeToFile(res.reader, this.downloadAssetFile);
}
/**
* 重置状态
*/
resetState() {
this.isDownload = false;
this.fileTotalSize = 0;
this.bufferPos = 0;
this.processLastTime = 0;
this.downloadFilename = "";
}
/**
* 以静态资源环境下下载
*/
async getAssetsSize() {
const fileInfoRes = await fetch(this.url, {
method: "HEAD"
});
const headers = fileInfoRes.headers;
const fileSize = headers.get("Content-Length");
return Number(fileSize);
}
async downloadAssetFile(startPos = 0) {
const endPos = this.limitSize + startPos;
const res = await fetch(this.url, {
method: "GET",
headers: {
"Range": `bytes=${startPos}-${endPos}`
}
});
const headers = res.headers;
const size = Number(headers.get("Content-Length"));
const reader = res.body.getReader();
const result = {
res,
reader,
size
};
return result;
}
/**
* 测试函数
*/
async debugFetch() {
const res = await fetch(this.url, {
method: "GET",
headers: {
"Range": `bytes=${19911656918}-`
}
});
console.log(res);
}
/**
* readableStream 写入 writeableStream核心处理,采用背压机制
* @param reader readable Reader
* @param downloadFunc 下载函数
* @private
*/
async pipeToFile(reader, downloadFunc) {
const fileStream = streamSaver.createWriteStream(this.downloadFilename, {
size: this.fileTotalSize
});
const writer = fileStream.getWriter();
// 分片循环下载
while (this.bufferPos < this.fileTotalSize) {
let done = false; // 本次HTTP range是否写入完毕
// 循环读取二进制并写入writeable stream
while (!done) {
const bufferRes = await reader.read();
const buffer = bufferRes.value;
done = bufferRes.done;
if (!done) {
await writer.ready.then(async () => {
await writer.write(buffer);
this.bufferPos += buffer.length;
// 500ms间隔执行一次钩子(简单防抖)
if (performance.now() - this.processLastTime >= 500) {
this.processHandler.call(this);
this.processLastTime = performance.now();
}
});
}
}
if (this.bufferPos < this.fileTotalSize) {
// 获取下一个range范围的二进制流
const retryRes = await downloadFunc.call(this, this.bufferPos);
reader = retryRes.reader;
}
}
await writer.ready.then(() => {
writer.close();
});
await writer.closed.then(() => {
this.processHandler.call(this);
console.log("✅ 下载完毕");
this.resetState();
});
}
}
</script>
<script>
const btn = document.querySelector(".download");
const downloader = new OversizeFileDownloader({
url: "/api/",
downloadFilename: `${Date.now()}.mp4`,
});
btn.addEventListener("click", () => {
downloader.downloadAssetsStater();
});
</script>
</body>
</html>