Um Dateien über HTTP mit Bun hochzuladen, verwenden Sie die FormData API. Beginnen wir mit einem HTTP-Server, der ein einfaches HTML-Webformular bereitstellt.
const server = Bun.serve({
port: 4000,
async fetch(req) {
const url = new URL(req.url);
// index.html für Root-Pfad zurückgeben
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}`);Wir können unser HTML-Formular in einer anderen Datei, index.html, definieren.
<!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>An diesem Punkt können wir den Server starten und localhost:4000 besuchen, um unser Formular zu sehen.
bun run index.ts
Listening on http://localhost:4000Unser Formular sendet eine POST-Anfrage an den /action-Endpunkt mit den Formulardaten. Verarbeiten wir diese Anfrage in unserem Server.
Zuerst verwenden wir die .formData() Methode auf der eingehenden Request, um ihren Inhalt asynchron in eine FormData-Instanz zu parsen. Dann können wir die .get() Methode verwenden, um den Wert der name- und profilePicture-Felder zu extrahieren. Hier entspricht name einem string und profilePicture ist ein Blob.
Schließlich schreiben wir das Blob mit Bun.write() auf die Festplatte.
const server = Bun.serve({
port: 4000,
async fetch(req) {
const url = new URL(req.url);
// index.html für Root-Pfad zurückgeben
if (url.pathname === "/")
return new Response(Bun.file("index.html"), {
headers: {
"Content-Type": "text/html",
},
});
// Formdata bei /action parsen
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 auf Festplatte schreiben
await Bun.write("profilePicture.png", profilePicture);
return new Response("Success");
}
return new Response("Not Found", { status: 404 });
},
});