0

I'm trying to upload a file to Cloudflare R2 with S3 API, but I'm getting an error. My code is as follows:

import { S3Client, PutObjectCommand, and GetObjectCommand } from '@aws-sdk/client-s3';

const client = new S3Client({
    region: 'auto',
    endpoint: `https://${import.meta.env.VITE_CLOUDFLARE_ACCOUNT_ID}.r2.cloudflarestorage.com`,
    credentials: {
        accessKeyId: `${import.meta.env.VITE_CLOUDFLARE_ACCESSS_KEY_ID}`,
        secretAccessKey: `${import.meta.env.VITE_CLOUDFLARE_SECRET_ACCESSS_KEY_ID}`
    }
});

export async function uploadCloudflareFile(blob: Blob, path: string): Promise<string> {
    const command = new PutObjectCommand({
        Bucket: 'voclone',
        Key: path,
        Body: blob,
        ContentType: blob.type
    });

    try {
        await client.send(command);
        const url = `https://${import.meta.env.VITE_CLOUDFLARE_ACCOUNT_ID}.r2.cloudflarestorage.com/voclone/${path}`;
        return url;
    } catch (error) {
        console.error("Error occurred while uploading file:", error);
        throw error;
    }
}

export async function downloadCloudflareFile(url: string) {
    try {
        const response = await fetch(url);
        const blob = await response.blob();
        return blob;
    } catch (error) {
        console.error("Error occurred while downloading file:", error);
    }
}

When I try to upload a file, the response is:

Access to fetch at 'https://voclone.8653f6e6a14c29627349579e49119562.r2.cloudflarestorage.com/models/jnini-jfgygg82hgox9tpv9ws8zh?x-id=PutObject' from origin 'http://localhost:5173' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

my cors.json clientside is:

[
    {
            "origin": ["*"],
            "method": ["GET", "PUT"],
            "maxAgeSeconds": 3600,
            "allowedHeaders": [
                "Content-Type",
                "X-Amz-Date",
                "Authorization",
                "X-Api-Key",
                "X-Amz-Security-Token",
                "X-Amz-User-Agent"
            ],
            "exposeHeaders": ["ETag"]
        }
]

Not sure what else I can do here. Anyone have any ideas?

Thanks!

eng
  • 443
  • 1
  • 4
  • 10
Ruder Buster
  • 219
  • 2
  • 14

0 Answers0