Per caricare file via HTTP con Bun, usa l'API FormData. Iniziamo con un server HTTP che serve un semplice form web HTML.
const server = Bun.serve({
port: 4000,
async fetch(req) {
const url = new URL(req.url);
// restituisce index.html per il percorso root
if (url.pathname === "/")
return new Response(Bun.file("index.html"), {
headers: {
"Content-Type": "text/html",
},
});
return new Response("Not Found", { status: 404 });
},
});
console.log(`In ascolto su http://localhost:${server.port}`);Possiamo definire il nostro form HTML in un altro file, index.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="Nome" />
<input type="file" name="profilePicture" />
<input type="submit" value="Invia" />
</form>
</body>
</html>A questo punto, possiamo eseguire il server e visitare localhost:4000 per vedere il nostro form.
bun run index.ts
In ascolto su http://localhost:4000Il nostro form invierà una richiesta POST all'endpoint /action con i dati del form. Gestiamo quella richiesta nel nostro server.
Prima usiamo il metodo .formData() sulla Request in entrata per analizzare in modo asincrono il suo contenuto in un'istanza FormData. Poi possiamo usare il metodo .get() per estrarre il valore dei campi name e profilePicture. Qui name corrisponde a una string e profilePicture è un Blob.
Infine, scriviamo il Blob su disco usando Bun.write().
const server = Bun.serve({
port: 4000,
async fetch(req) {
const url = new URL(req.url);
// restituisce index.html per il percorso root
if (url.pathname === "/")
return new Response(Bun.file("index.html"), {
headers: {
"Content-Type": "text/html",
},
});
// analizza formdata su /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("Devi caricare un'immagine del profilo.");
// scrive profilePicture su disco
await Bun.write("profilePicture.png", profilePicture);
return new Response("Successo");
}
return new Response("Not Found", { status: 404 });
},
});