const ALLOWED = { 'image/jpeg': 'jpg', 'image/png': 'png', 'image/gif': 'gif', 'audio/mpeg': 'mp3', 'video/mp4': 'mp4', }; const MAX = 100 * 1024 * 1024; const PAGE = ` smootfly.my.id

Upload File

JPG, PNG, GIF, MP3, MP4 (maks 100 MB)

URL kamu:


`; export default { async fetch(request, env) { const url = new URL(request.url); // Halaman upload if (request.method === 'GET' && url.pathname === '/') { return new Response(PAGE, { headers: { 'content-type': 'text/html; charset=utf-8' } }); } // Proses upload if (request.method === 'POST' && url.pathname === '/upload') { const form = await request.formData(); const file = form.get('file'); if (!file || typeof file === 'string') return json({ error: 'Tidak ada file' }, 400); if (!ALLOWED[file.type]) return json({ error: 'Tipe file tidak didukung' }, 400); if (file.size > MAX) return json({ error: 'File maks 100 MB' }, 400); const name = `${randomId(8)}.${ALLOWED[file.type]}`; await env.BUCKET.put(name, file.stream(), { httpMetadata: { contentType: file.type }, }); return json({ url: `${url.origin}/${name}` }); } // Akses file: /aB3xK9qP.jpg if (request.method === 'GET' && url.pathname.length > 1) { const name = url.pathname.slice(1); if (!/^[A-Za-z0-9]+\.(jpg|png|gif|mp3|mp4)$/.test(name)) { return new Response('Tidak ditemukan', { status: 404 }); } const obj = await env.BUCKET.get(name); if (!obj) return new Response('Tidak ditemukan', { status: 404 }); return new Response(obj.body, { headers: { 'content-type': obj.httpMetadata.contentType, 'cache-control': 'public, max-age=31536000', }, }); } return new Response('Not found', { status: 404 }); }, }; function randomId(len) { const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; const bytes = crypto.getRandomValues(new Uint8Array(len)); return Array.from(bytes, b => chars[b % chars.length]).join(''); } function json(obj, status = 200) { return new Response(JSON.stringify(obj), { status, headers: { 'content-type': 'application/json' }, }); }