Для загрузки файлов через HTTP в Bun используйте API FormData. Начнём с HTTP-сервера, который обслуживает простую HTML-форму.
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}`);Определим нашу HTML-форму в другом файле 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, чтобы увидеть нашу форму.
bash
bun run index.ts
Listening on http://localhost:4000Наша форма отправит POST-запрос к эндпоинту /action с данными формы. Обработаем этот запрос в нашем сервере.
Сначала используем метод .formData() входящего Request для асинхронного разбора его содержимого в экземпляр FormData. Затем можем использовать метод .get() для извлечения значений полей name и profilePicture. Здесь name соответствует string, а profilePicture — это Blob.
Наконец, записываем Blob на диск с помощью Bun.write().
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",
},
});
// разобрать formdata на /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.");
// записать profilePicture на диск
await Bun.write("profilePicture.png", profilePicture);
return new Response("Success");
}
return new Response("Not Found", { status: 404 });
},
});