لرفع الملفات عبر HTTP مع Bun، استخدم واجهة برمجة التطبيقات 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("يجب رفع صورة شخصية.");
// كتابة profilePicture إلى القرص
await Bun.write("profilePicture.png", profilePicture);
return new Response("Success");
}
return new Response("Not Found", { status: 404 });
},
});