Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Cloudflare Worker Script (UPDATED - worker.js)
- export default {
- async fetch(request, env, ctx) {
- // Add CORS headers function
- const corsHeaders = {
- 'Access-Control-Allow-Origin': '*', // Replace with your frontend domain in production
- 'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
- 'Access-Control-Allow-Headers': 'Content-Type',
- };
- // Handle CORS preflight requests
- if (request.method === 'OPTIONS') {
- return new Response(null, { headers: corsHeaders });
- }
- // Check R2 binding
- if (!env.R2_UPLOAD_BUCKET) {
- return new Response(JSON.stringify({ error: "R2 bucket binding 'R2_UPLOAD_BUCKET' not configured." }), {
- status: 500,
- headers: { ...corsHeaders, 'Content-Type': 'application/json' },
- });
- }
- // Define Public URL Base *****CHANGE THIS TO YOUR URL******
- const PUBLIC_URL_BASE = 'https://pub-b531dfa32c0.r2.dev';
- try {
- // Handle POST for uploads
- if (request.method === 'POST') {
- const formData = await request.formData();
- const file = formData.get('image');
- if (!file || typeof file === 'string') {
- return new Response(JSON.stringify({ error: 'File not provided or invalid' }), {
- status: 400,
- headers: { ...corsHeaders, 'Content-Type': 'application/json' },
- });
- }
- const fileExtension = file.name.split('.').pop() || 'bin';
- const uniqueFileName = `${Date.now()}-${Math.random().toString(36).substring(2, 15)}.${fileExtension}`;
- await env.R2_UPLOAD_BUCKET.put(uniqueFileName, file.stream(), {
- httpMetadata: { contentType: file.type || 'application/octet-stream' },
- });
- const publicUrl = `${PUBLIC_URL_BASE}/${uniqueFileName}`;
- return new Response(JSON.stringify({ success: true, url: publicUrl }), {
- status: 200,
- headers: { ...corsHeaders, 'Content-Type': 'application/json' },
- });
- }
- // Handle GET for listing images
- else if (request.method === 'GET') {
- // List objects in the bucket
- const listed = await env.R2_UPLOAD_BUCKET.list();
- // Map objects to their public URLs
- const imageURLs = listed.objects.map(obj => `${PUBLIC_URL_BASE}/${obj.key}`);
- return new Response(JSON.stringify({ success: true, images: imageURLs }), {
- status: 200,
- headers: { ...corsHeaders, 'Content-Type': 'application/json' },
- });
- }
- // Handle other methods
- else {
- return new Response('Method Not Allowed', { status: 405, headers: corsHeaders });
- }
- } catch (error) {
- console.error('Worker Error:', error);
- return new Response(JSON.stringify({ error: 'Failed to process request.', details: error.message }), {
- status: 500,
- headers: { ...corsHeaders, 'Content-Type': 'application/json' },
- });
- }
- },
- };
Advertisement
Add Comment
Please, Sign In to add comment