若要使用 Bun 透過 HTTP 上傳檔案,請使用 FormData
API。我們從提供簡單 HTML 網路表單的 HTTP 伺服器開始。
const server = Bun.serve({
port: 4000,
async fetch(req) {
const url = new URL(req.url);
// return index.html for root path
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 https://127.0.0.1:${server.port}`);
我們可以在另一個檔案 index.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
來查看我們的表單。
bun run index.ts
Listening on https://127.0.0.1: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);
// return index.html for root path
if (url.pathname === "/")
return new Response(Bun.file("index.html"), {
headers: {
"Content-Type": "text/html",
},
});
// parse formdata at /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.');
// write profilePicture to disk
await Bun.write('profilePicture.png', profilePicture);
return new Response("Success");
}
return new Response("Not Found", { status: 404 });
},
});