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

폼은 폼 데이터와 함께 POST 요청을 /action 엔드포인트로 보냅니다. 서버에서 이 요청을 처리해 보겠습니다.

먼저 들어오는 Request.formData() 메서드를 사용하여 내용을 FormData 인스턴스로 비동기적으로 파싱합니다. 그런 다음 .get() 메서드를 사용하여 nameprofilePicture 필드의 값을 추출할 수 있습니다. 여기서 namestring 에 해당하고 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 에서 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("Must upload a profile picture."); 
      // profilePicture 을 디스크에 쓰기
      await Bun.write("profilePicture.png", profilePicture); 
      return new Response("Success"); 
    } 

    return new Response("Not Found", { status: 404 });
  },
});

Bun by www.bunjs.com.cn 편집