執行環境套件管理器打包器測試執行器程式碼檢查格式化指南參考部落格意見回饋

使用 FormData 通過 HTTP 上傳檔案

要通過 HTTP 使用 Bun 上傳檔案,請使用 FormData API。首先,建立一個提供 HTML 表單的 HTTP 伺服器。

index.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>表單</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 寫入磁碟。

index.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 // [!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 });
  },
});