要在 Bun 中通过 HTTP 上传文件,请使用 FormData API。让我们从一个提供简单 HTML 网页表单的 HTTP 服务器开始。
ts
const server = Bun.serve({
port: 4000,
async fetch(req) {
const url = new URL(req.url);
// 为根路径返回 index.html
if (url.pathname === "/")
return new Response(Bun.file("index.html"), {
headers: {
"Content-Type": "text/html",
},
});
return new Response("Not Found", { status: 404 });
},
});
console.log(`Listening on http://localhost:${server.port}`);我们可以在另一个文件 index.html 中定义我们的 HTML 表单。
html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Form</title>
</head>
<body>
<form action="/action" method="post" enctype="multipart/form-data">
<input type="text" name="name" placeholder="Name" />
<input type="file" name="profilePicture" />
<input type="submit" value="Submit" />
</form>
</body>
</html>此时,我们可以运行服务器并访问 localhost:4000 来查看我们的表单。
bash
bun run index.ts
Listening on http://localhost:4000我们的表单将向 /action 端点发送一个带有表单数据的 POST 请求。让我们在我们的服务器中处理该请求。
首先,我们使用传入 Request 的 .formData() 方法将其内容异步解析为 FormData 实例。然后我们可以使用 .get() 方法提取 name 和 profilePicture 字段的值。这里 name 对应于 string,而 profilePicture 是 Blob。
最后,我们使用 Bun.write() 将 Blob 写入磁盘。
ts
const server = Bun.serve({
port: 4000,
async fetch(req) {
const url = new URL(req.url);
// 为根路径返回 index.html
if (url.pathname === "/")
return new Response(Bun.file("index.html"), {
headers: {
"Content-Type": "text/html",
},
});
// 在 /action 解析表单数据
if (url.pathname === "/action") {
const formdata = await req.formData();
const name = formdata.get("name");
const profilePicture = formdata.get("profilePicture");
if (!profilePicture) throw new Error("Must upload a profile picture.");
// 将 profilePicture 写入磁盘
await Bun.write("profilePicture.png", profilePicture);
return new Response("Success");
}
return new Response("Not Found", { status: 404 });
},
});