Create the POST endpoint
Import the APIRoute type from "astro" and create a POST endpoint that accepts the locals parameter. This endpoint will handle file uploads to the R2 bucket, including CORS preflight requests and form data processing.
Initialize API and handle CORS
Initialize the API utility with the origin set in your environment variables and handle CORS preflight requests. The OPTIONS method is used by browsers to check if the cross-origin request is allowed before sending the actual file data.
Key concepts:
- CORS preflight: Browsers send OPTIONS requests to check cross-origin permissions
- API initialization: Set up the API utility with the correct origin for CORS headers
Validate bucket configuration
Access the CLOUD_FILES binding and verify that the Object Storage bucket is properly configured. If the bucket isn't available, return a 500 error with a descriptive message to help with debugging.
Process form data and validate file
Extract the file from the FormData object and validate that it's a proper File instance.
Generate unique filename
Create a unique filename by combining a timestamp with the original filename. This prevents filename collisions and ensures each upload has a unique identifier. Extract the file extension to preserve the file type.
Upload file to the bucket
Use the .put() method to upload the file to the Object Storage bucket with the generated filename. Set the httpMetadata to include the file's content type, which is essential for proper file serving later.
Return success response
Return a success response with file details including the generated filename, Object Storage key, file size, and content type. This information is useful for the client to track the uploaded file.