forked from zzzzzhowie/file-upload
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.vue
More file actions
330 lines (323 loc) · 9.44 KB
/
App.vue
File metadata and controls
330 lines (323 loc) · 9.44 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
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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
<template>
<div id="app">
<div>
<input
type="file"
:disabled="status !== Status.wait"
@change="handleFileChange"
/>
<el-button @click="handleUpload" :disabled="uploadDisabled"
>upload</el-button
>
<el-button @click="handleResume" v-if="status === Status.pause"
>resume</el-button
>
<el-button
v-else
:disabled="status !== Status.uploading || !container.hash"
@click="handlePause"
>pause</el-button
>
<el-button @click="handleDelete">delete</el-button>
<el-button @click="handleDownLoad">download</el-button>
</div>
<div>
<div>
<div>calculate chunk hash</div>
<el-progress :percentage="hashPercentage"></el-progress>
</div>
<div>
<div>percentage</div>
<el-progress :percentage="fakeUploadPercentage"></el-progress>
</div>
</div>
<el-table :data="data">
<el-table-column
prop="hash"
label="chunk hash"
align="center"
></el-table-column>
<el-table-column label="size(KB)" align="center" width="120">
<template v-slot="{ row }">
{{ row.size | transformByte }}
</template>
</el-table-column>
<el-table-column label="percentage" align="center">
<template v-slot="{ row }">
<el-progress
:percentage="row.percentage"
color="#909399"
></el-progress>
</template>
</el-table-column>
</el-table>
</div>
</template>
<script>
// import saveAs from "file-saver";
// 切片大小
// chunk size
const SIZE = 10 * 1024 * 1024;
const Status = {
wait: "wait",
pause: "pause",
uploading: "uploading"
};
export default {
name: "app",
filters: {
transformByte(val) {
return Number((val / 1024).toFixed(0));
}
},
data: () => ({
Status,
container: {
file: null,
hash: "",
worker: null
},
hashPercentage: 0,
data: [],
requestList: [],
status: Status.wait,
// 当暂停时会取消 xhr 导致进度条后退
// 为了避免这种情况,需要定义一个假的进度条
// use fake progress to avoid progress backwards when upload is paused
fakeUploadPercentage: 0
}),
computed: {
uploadDisabled() {
return (
!this.container.file ||
[Status.pause, Status.uploading].includes(this.status)
);
},
uploadPercentage() {
if (!this.container.file || !this.data.length) return 0;
const loaded = this.data
.map(item => item.size * item.percentage)
.reduce((acc, cur) => acc + cur);
return parseInt((loaded / this.container.file.size).toFixed(2));
}
},
watch: {
uploadPercentage(now) {
if (now > this.fakeUploadPercentage) {
this.fakeUploadPercentage = now;
}
}
},
methods: {
async handleDelete() {
const { data } = await this.request({
url: "http://localhost:3000/delete"
});
if (JSON.parse(data).code === 0) {
this.$message.success("delete success");
}
},
handlePause() {
this.status = Status.pause;
this.resetData();
},
resetData() {
this.requestList.forEach(xhr => xhr?.abort());
this.requestList = [];
if (this.container.worker) {
this.container.worker.onmessage = null;
}
},
async handleResume() {
this.status = Status.uploading;
const { uploadedList } = await this.verifyUpload(
this.container.file.name,
this.container.hash
);
await this.uploadChunks(uploadedList);
},
// xhr
request({
url,
method = "post",
data,
headers = {},
onProgress = e => e,
requestList
}) {
return new Promise(resolve => {
const xhr = new XMLHttpRequest();
xhr.upload.onprogress = onProgress;
xhr.open(method, url);
Object.keys(headers).forEach(key =>
xhr.setRequestHeader(key, headers[key])
);
xhr.send(data);
xhr.onload = e => {
// 将请求成功的 xhr 从列表中删除
// remove xhr which status is success
if (requestList) {
const xhrIndex = requestList.findIndex(item => item === xhr);
requestList.splice(xhrIndex, 1);
}
resolve({
data: e.target.response
});
};
// 暴露当前 xhr 给外部
// export xhr
requestList?.push(xhr);
});
},
// 生成文件切片
// create file chunk
createFileChunk(file, size = SIZE) {
const fileChunkList = [];
let cur = 0;
while (cur < file.size) {
fileChunkList.push({ file: file.slice(cur, cur + size) });
cur += size;
}
return fileChunkList;
},
// 生成文件 hash(web-worker)
// use web-worker to calculate hash
calculateHash(fileChunkList) {
return new Promise(resolve => {
this.container.worker = new Worker("/hash.js");
this.container.worker.postMessage({ fileChunkList });
this.container.worker.onmessage = e => {
const { percentage, hash } = e.data;
this.hashPercentage = percentage;
if (hash) {
resolve(hash);
}
};
});
},
handleFileChange(e) {
const [file] = e.target.files;
if (!file) return;
this.resetData();
Object.assign(this.$data, this.$options.data());
this.container.file = file;
},
async handleUpload() {
if (!this.container.file) return;
this.status = Status.uploading;
const fileChunkList = this.createFileChunk(this.container.file);
this.container.hash = await this.calculateHash(fileChunkList);
const { shouldUpload, uploadedList } = await this.verifyUpload(
this.container.file.name,
this.container.hash
);
if (!shouldUpload) {
this.$message.success("skip upload:file upload success");
this.status = Status.wait;
return;
}
this.data = fileChunkList.map(({ file }, index) => ({
fileHash: this.container.hash,
index,
hash: this.container.hash + "-" + index,
chunk: file,
size: file.size,
percentage: uploadedList.includes(index) ? 100 : 0
}));
await this.uploadChunks(uploadedList);
},
// 上传切片,同时过滤已上传的切片
// upload chunks and filter uploaded chunks
async uploadChunks(uploadedList = []) {
const requestList = this.data
.filter(({ hash }) => !uploadedList.includes(hash))
.map(({ chunk, hash, index }) => {
const formData = new FormData();
formData.append("chunk", chunk);
formData.append("hash", hash);
formData.append("filename", this.container.file.name);
formData.append("fileHash", this.container.hash);
return { formData, index };
})
.map(({ formData, index }) =>
this.request({
url: "http://localhost:3000",
data: formData,
onProgress: this.createProgressHandler(this.data[index]),
requestList: this.requestList
})
);
await Promise.all(requestList);
// 之前上传的切片数量 + 本次上传的切片数量 = 所有切片数量时合并切片
// merge chunks when the number of chunks uploaded before and
// the number of chunks uploaded this time
// are equal to the number of all chunks
if (uploadedList.length + requestList.length === this.data.length) {
await this.mergeRequest();
}
},
// 通知服务端合并切片
// notify server to merge chunks
async mergeRequest() {
await this.request({
url: "http://localhost:3000/merge",
headers: {
"content-type": "application/json"
},
data: JSON.stringify({
size: SIZE,
fileHash: this.container.hash,
filename: this.container.file.name
})
});
this.$message.success("upload success");
this.status = Status.wait;
},
// 根据 hash 验证文件是否曾经已经被上传过
// 没有才进行上传
// verify that the file has been uploaded based on the hash
// skip if uploaded
async verifyUpload(filename, fileHash) {
const { data } = await this.request({
url: "http://localhost:3000/verify",
headers: {
"content-type": "application/json"
},
data: JSON.stringify({
filename,
fileHash
})
});
return JSON.parse(data);
},
// 用闭包保存每个 chunk 的进度数据
// use closures to save progress data for each chunk
createProgressHandler(item) {
return e => {
const percentage = parseInt(String((e.loaded / e.total) * 100));
item.percentage =
item.percentage > percentage ? item.percentage : percentage;
};
},
// 下载上传的文件
async handleDownLoad() {
const filename = this.container.file.name;
const fileHash = this.container.hash;
const data = await this.request({
url: "http://localhost:3000/download",
headers: {
responseType: "blob",
"content-type": "application/json"
},
data: JSON.stringify({
filename,
fileHash
})
});
console.log(data);
// const blob = new Blob([data]);
// saveAs(blob, "file.zip");
}
}
};
</script>