Skip to main content
要使用 Bun 通过 HTTP 上传文件,请使用 FormData API。让我们从一个提供简单 HTML 网页表单的 HTTP 服务器开始。
https://mintcdn.com/ikxin/RzFFGbzo0-4huILA/icons/typescript.svg?fit=max&auto=format&n=RzFFGbzo0-4huILA&q=85&s=a3dffd2241f05776d3bd25171d0c5a79index.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 表单。
index.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 来查看我们的表单。
bun run index.ts
Listening on http://localhost:4000

我们的表单会向 /action 端点发送包含表单数据的 POST 请求。让我们在服务器端处理该请求。 首先,我们使用传入 Request 对象上的 .formData() 方法异步解析其内容为 FormData 实例。然后,我们可以使用 .get() 方法提取 nameprofilePicture 字段的值。其中 name 是一个 stringprofilePicture 是一个 Blob 最后,我们使用 Bun.write()Blob 写入磁盘。
https://mintcdn.com/ikxin/RzFFGbzo0-4huILA/icons/typescript.svg?fit=max&auto=format&n=RzFFGbzo0-4huILA&q=85&s=a3dffd2241f05776d3bd25171d0c5a79index.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 路径解析 formdata
    if (url.pathname === "/action") { 
      const formdata = await req.formData(); 
      const name = formdata.get("name"); 
      const profilePicture = formdata.get("profilePicture"); 
      if (!profilePicture) throw new Error("必须上传个人头像。"); 
      // 将 profilePicture 写入磁盘
      await Bun.write("profilePicture.png", profilePicture); 
      return new Response("成功"); 
    } 

    return new Response("未找到", { status: 404 });
  },
});