-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
72 lines (65 loc) · 2.26 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>image-uploader</title>
</head>
<body>
<h1>image-uploader</h1>
<input type="file" />
<script>
// createImage(size: number, type: number): Promise<{
// formData: [string, string][];
// method: string;
// url: string;
// }>
async function createImage(size, type) {
const response = await fetch("/images", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
content_length: size,
...type.length > 0 ? { content_type: type } : {}
}),
});
if (response.status !== 200) throw new Error("createImage failed");
const { form_data: formData, method, url } = await response.json();
return { formData, method, url };
}
// uploadImage(
// url: string,
// method: string,
// formData: [string, string][],
// file: File
// ): Promise<void>
async function uploadImage(url, method, formData, file) {
const init = new FormData();
const body = formData.reduce((formData, [name, value]) => {
formData.set(name, value);
return formData;
}, init);
body.set("file", file);
const response = await fetch(url, { body, method });
if (response.status !== 204) throw new Error("uploadImage failed");
const responseBody = await response.text();
if (responseBody !== "") throw new Error("uploadImage response body is invalid");
}
function onChange(event) {
if (event.target.files.length === 0) return;
const file = event.target.files[0];
// <https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file#getting_information_on_selected_files>
console.log(`file selected (size = ${file.size}, type = ${file.type})`);
void (async () => {
const { formData, method, url } = await createImage(file.size, file.type);
await uploadImage(url, method, formData, file);
})();
}
function main() {
const element = document.querySelector("input[type='file']");
if (element === null) throw new Error("input[type='file'] not found");
element.addEventListener("change", onChange);
}
main();
</script>
</body>
</html>