使用 FormData 通过 HTTP 上传文件
要通过 HTTP 使用 Bun 上传文件,请使用 FormData API。首先,创建一个提供 HTML 表单的 HTTP 服务器。
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 表单。
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>表单</title>
</head>
<body>
<form action="/action" method="post" enctype="multipart/form-data">
<input type="text" name="name" placeholder="姓名" />
<input type="file" name="profilePicture" />
<input type="submit" value="提交" />
</form>
</body>
</html>
运行服务器并访问 localhost:4000 查看表单。
bash
bun run index.ts
Listening on http://localhost:4000
表单会将表单数据通过 POST 请求发送到 /action 端点。在服务器中处理该请求。
首先,在传入的 Request 上调用 .formData(),以异步地将其内容解析为 FormData 实例。然后使用 .get() 提取 name 和 profilePicture 字段;name 是一个 string,而 profilePicture 是一个 Blob。
最后,使用 Bun.write() 将 Blob 写入磁盘。
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 路径解析 formdata // [!code ++]
if (url.pathname === "/action") { // [!code ++]
const formdata = await req.formData(); // [!code ++]
const name = formdata.get("name"); // [!code ++]
const profilePicture = formdata.get("profilePicture"); // [!code ++]
if (!profilePicture) throw new Error("必须上传个人头像。"); // [!code ++]
// 将 profilePicture 写入磁盘 // [!code ++]
await Bun.write("profilePicture.png", profilePicture); // [!code ++]
return new Response("成功"); // [!code ++]
} // [!code ++]
return new Response("未找到", { status: 404 });
},
});