Guest User

Wrokers.js code

a guest
Apr 2nd, 2025
36
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.95 KB | None | 0 0
  1. // Cloudflare Worker Script (UPDATED - worker.js)
  2.  
  3. export default {
  4. async fetch(request, env, ctx) {
  5. // Add CORS headers function
  6. const corsHeaders = {
  7. 'Access-Control-Allow-Origin': '*', // Replace with your frontend domain in production
  8. 'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
  9. 'Access-Control-Allow-Headers': 'Content-Type',
  10. };
  11.  
  12. // Handle CORS preflight requests
  13. if (request.method === 'OPTIONS') {
  14. return new Response(null, { headers: corsHeaders });
  15. }
  16.  
  17. // Check R2 binding
  18. if (!env.R2_UPLOAD_BUCKET) {
  19. return new Response(JSON.stringify({ error: "R2 bucket binding 'R2_UPLOAD_BUCKET' not configured." }), {
  20. status: 500,
  21. headers: { ...corsHeaders, 'Content-Type': 'application/json' },
  22. });
  23. }
  24.  
  25. // Define Public URL Base *****CHANGE THIS TO YOUR URL******
  26. const PUBLIC_URL_BASE = 'https://pub-b531dfa32c0.r2.dev';
  27.  
  28. try {
  29. // Handle POST for uploads
  30. if (request.method === 'POST') {
  31. const formData = await request.formData();
  32. const file = formData.get('image');
  33.  
  34. if (!file || typeof file === 'string') {
  35. return new Response(JSON.stringify({ error: 'File not provided or invalid' }), {
  36. status: 400,
  37. headers: { ...corsHeaders, 'Content-Type': 'application/json' },
  38. });
  39. }
  40.  
  41. const fileExtension = file.name.split('.').pop() || 'bin';
  42. const uniqueFileName = `${Date.now()}-${Math.random().toString(36).substring(2, 15)}.${fileExtension}`;
  43.  
  44. await env.R2_UPLOAD_BUCKET.put(uniqueFileName, file.stream(), {
  45. httpMetadata: { contentType: file.type || 'application/octet-stream' },
  46. });
  47.  
  48. const publicUrl = `${PUBLIC_URL_BASE}/${uniqueFileName}`;
  49.  
  50. return new Response(JSON.stringify({ success: true, url: publicUrl }), {
  51. status: 200,
  52. headers: { ...corsHeaders, 'Content-Type': 'application/json' },
  53. });
  54. }
  55. // Handle GET for listing images
  56. else if (request.method === 'GET') {
  57. // List objects in the bucket
  58. const listed = await env.R2_UPLOAD_BUCKET.list();
  59.  
  60. // Map objects to their public URLs
  61. const imageURLs = listed.objects.map(obj => `${PUBLIC_URL_BASE}/${obj.key}`);
  62.  
  63. return new Response(JSON.stringify({ success: true, images: imageURLs }), {
  64. status: 200,
  65. headers: { ...corsHeaders, 'Content-Type': 'application/json' },
  66. });
  67. }
  68. // Handle other methods
  69. else {
  70. return new Response('Method Not Allowed', { status: 405, headers: corsHeaders });
  71. }
  72.  
  73. } catch (error) {
  74. console.error('Worker Error:', error);
  75. return new Response(JSON.stringify({ error: 'Failed to process request.', details: error.message }), {
  76. status: 500,
  77. headers: { ...corsHeaders, 'Content-Type': 'application/json' },
  78. });
  79. }
  80. },
  81. };
Advertisement
Add Comment
Please, Sign In to add comment