Skip to content

要在 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() 方法提取 nameprofilePicture 字段的值。這裡 name 對應於 string,而 profilePictureBlob

最後,我們使用 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 });
  },
});

Bun學習網由www.bunjs.com.cn整理維護