Para subir archivos vía HTTP con Bun, usa la API FormData. Comencemos con un servidor HTTP que sirve un simple formulario web HTML.
const server = Bun.serve({
port: 4000,
async fetch(req) {
const url = new URL(req.url);
// devolver index.html para la ruta raíz
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});
---
Podemos definir nuestro formulario HTML en otro archivo, `index.html`.
```html 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="Name" />
<input type="file" name="profilePicture" />
<input type="submit" value="Submit" />
</form>
</body>
</html>En este punto, podemos ejecutar el servidor y visitar localhost:4000 para ver nuestro formulario.
bun run index.ts
Listening on http://localhost:4000Nuestro formulario enviará una solicitud POST al endpoint /action con los datos del formulario. Manejemos esa solicitud en nuestro servidor.
Primero usamos el método .formData() en la Request entrante para analizar asíncronamente su contenido a una instancia FormData. Luego podemos usar el método .get() para extraer el valor de los campos name y profilePicture. Aquí name corresponde a un string y profilePicture es un Blob.
Finalmente, escribimos el Blob en disco usando Bun.write().
const server = Bun.serve({
port: 4000,
async fetch(req) {
const url = new URL(req.url);
// devolver index.html para la ruta raíz
if (url.pathname === "/")
return new Response(Bun.file("index.html"), {
headers: {
"Content-Type": "text/html",
},
});
// analizar formdata en /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.");
// escribir profilePicture en disco
await Bun.write("profilePicture.png", profilePicture);
return new Response("Success");
}
return new Response("Not Found", { status: 404 });
},
});