-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathupload.html
More file actions
201 lines (175 loc) · 6 KB
/
upload.html
File metadata and controls
201 lines (175 loc) · 6 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
<!DOCTYPE html>
<html>
<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>Multipart upload</title>
</head>
<body>
<label for="file">Choose file:</label>
<input type="file" id="file" name="file" />
<script>
const vodModuleUrl = `/api/vod`;
const getSupportedFiletypes = async () => {
const response = await fetch(vodModuleUrl + "/filetypes", {
headers: {
"Content-Type": "application/json",
},
});
const {
fileTypes: { Audio, Caption, Video },
} = await response.json();
return [Audio, Caption, Video].flat();
};
const startUpload = async ({ title, size, name }) => {
const response = await fetch(vodModuleUrl + "/files/start/", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
friendlyName: title,
fileSize: size,
name: name,
metadata: {},
}),
});
console.log("Uploading started");
return await response.json();
};
const uploadPart = async ({ blob, url }) => {
return fetch(url, {
method: "PUT",
headers: {
"Content-Type": "application/octet-stream",
"Access-Control-Allow-Origin": "*",
},
body: blob,
});
};
const getUploadUrlForPart = async ({ id, partNumber }) => {
const response = await fetch(
vodModuleUrl + `/files/${id}/part/${partNumber}`,
{
headers: {
"Content-Type": "application/json",
},
}
);
return await response.json();
};
const uploadComplete = async ({ fileId, parts, uploadId }) => {
return fetch(vodModuleUrl + "/files/complete/", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ fileId, parts, uploadId }),
});
};
const processChunk = async ({
fileName,
url,
blob,
partNumber,
}) => {
try {
const response = await uploadPart({ url, blob });
const eTag = response.headers.get("etag");
console.log(`Uploaded part ${partNumber} of ${fileName}`);
return { eTag, partNumber };
} catch (error) {
console.error(error);
}
};
const uploadFiles = async (file) => {
const fileName = file.name;
try {
const { fileId, multipartUrls, uploadId, partSize, partsCount, lastPartSize } =
await startUpload({
title: file.name, // change this property if you want to name asset differently than the file
name: file.name,
size: file.size,
});
const itemsCountInSingleCountGroup = multipartUrls.length;
const chunksGroupsCount = Math.ceil(
partsCount / itemsCountInSingleCountGroup
);
let chunksToUpload = partsCount;
let multipartUrlsToUpload = multipartUrls;
let parts = [];
for (const groupIndex of Array(chunksGroupsCount)
.fill(undefined)
.keys()) {
if (groupIndex !== 0) {
const nextChunkGroupLenght = Math.min(
itemsCountInSingleCountGroup,
chunksToUpload
);
const nextPartsUrls = await Promise.all(
Array(nextChunkGroupLenght)
.fill(undefined)
.map((_, index) =>
getUploadUrlForPart({
id: fileId,
partNumber:
groupIndex * itemsCountInSingleCountGroup + index + 1,
})
)
);
multipartUrlsToUpload = nextPartsUrls
.filter(Boolean)
.map((item) => item.url);
}
const chunksData = multipartUrlsToUpload.map((url, index) => {
const blob = file.slice(
partSize * (groupIndex * itemsCountInSingleCountGroup + index),
partSize *
(groupIndex * itemsCountInSingleCountGroup + index + 1)
);
const partNumber = groupIndex * itemsCountInSingleCountGroup + index + 1;
const isLastPart = partNumber === partsCount;
if (isLastPart) {
if (blob.size !== lastPartSize) {
// If you are reimplementing this code in a different programming language, verify that the last chunk of data has the expected size
throw new Error('Invalid last part size');
}
}
return {
fileName,
url,
blob,
partNumber:
groupIndex * itemsCountInSingleCountGroup + index + 1,
};
});
const results = await Promise.all(
chunksData.map(processChunk)
);
parts = parts.concat(results);
chunksToUpload = chunksToUpload - chunksData.length;
}
if (!parts?.length) {
return;
}
await uploadComplete({ fileId, parts, uploadId });
console.log("Upload complete");
} catch (error) {
console.error(error);
}
};
(async () => {
const supportedFiletypes = await getSupportedFiletypes();
const input = document.getElementById("file");
input.setAttribute("accept", supportedFiletypes);
input.addEventListener("change", async () => {
if (input.files.length === 1) {
const file = input.files[0];
await uploadFiles(file);
}
});
})();
</script>
</body>
</html>