Skip to content

Commit 93cf160

Browse files
committed
chore: Add file upload example
1 parent 727f4e2 commit 93cf160

2 files changed

Lines changed: 76 additions & 0 deletions

File tree

examples/file-upload/index.html

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
<!doctype html>
2+
<html lang="en">
3+
<head>
4+
<meta charset="UTF-8" />
5+
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
6+
<title>File Upload Example</title>
7+
</head>
8+
<body>
9+
<form action="/upload-one" method="POST" enctype="multipart/form-data">
10+
<input type="file" name="file" />
11+
<button>Upload One</button>
12+
</form>
13+
14+
<hr />
15+
16+
<form action="/upload-many" method="POST" enctype="multipart/form-data">
17+
<input type="file" name="files" multiple />
18+
<button>Upload Many</button>
19+
</form>
20+
</body>
21+
</html>

examples/file-upload/main.ts

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
import { createApp, HttpStatus } from "@aklinker1/zeta";
2+
import {
3+
NoResponse,
4+
UploadFileBody,
5+
UploadFilesBody,
6+
} from "@aklinker1/zeta/schema";
7+
import { resolve } from "node:path";
8+
import testPage from "./index.html";
9+
10+
async function writeFile(file: File): Promise<void> {
11+
const path = resolve("data", file.name);
12+
await Bun.write(path, file);
13+
console.log(`Saved ${file.name} to: ${path}`);
14+
}
15+
16+
const app = createApp()
17+
.post(
18+
"/upload-one",
19+
{
20+
body: UploadFileBody,
21+
responses: {
22+
[HttpStatus.Found]: NoResponse,
23+
},
24+
},
25+
async ({ body, status, set }) => {
26+
await writeFile(body);
27+
28+
// Redirect since the test webpage uses forms, not JS
29+
set.headers["Location"] = "/";
30+
return status(HttpStatus.Found, undefined);
31+
},
32+
)
33+
.post(
34+
"/upload-many",
35+
{
36+
body: UploadFilesBody,
37+
responses: {
38+
[HttpStatus.Found]: NoResponse,
39+
},
40+
},
41+
async ({ body, status, set }) => {
42+
for (const file of body) await writeFile(file);
43+
44+
// Redirect since the test webpage uses forms, not JS
45+
set.headers["Location"] = "/";
46+
return status(HttpStatus.Found, undefined);
47+
},
48+
);
49+
50+
Bun.serve({
51+
routes: {
52+
"/": testPage,
53+
"/**": app.build(),
54+
},
55+
});

0 commit comments

Comments
 (0)