Hello!

I am trying to upload a file to Spaces through the Javascript aws-sdk library.

I have an <input type="file" onChange={handleFileUpload}/> element, with this handler:

const onSelectFile = (e: any) => {
    if (e.target.files && e.target.files[0]) {
        uploadFile(e.target.files[0]);
    }
}

And the definition for uploadFile is:

import AWS from "aws-sdk";

const spacesEndpoint = new AWS.Endpoint("sgp1.digitaloceanspaces.com");

const s3 = new AWS.S3({
    endpoint: spacesEndpoint as any,
    accessKeyId: "---",
    secretAccessKey: "---"
});

export const uploadFile = async (file: any) => {
    const config = {
        Body: file,
        Bucket: "---",
        Key: "test",
    };
    s3.putObject(config)
        .on("build", request => {
            request.httpRequest.headers.Host="https://runbook.sgp1.digitaloceanspaces.com";
            request.httpRequest.headers["Content-Length"] = file.size;
            request.httpRequest.headers["Content-Type"] = "application/octet-stream";
            request.httpRequest.headers["x-amz-acl"] = "public-read";
            request.httpRequest.headers["Access-Control-Allow-Origin"] = "*";
        })
        .send((err) => {
            if (err) {
                console.log("Failed to upload file", `${err}`);
            }
        });
};

export default s3;

However, whenever I invoke this, I get the following errors:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://---.sgp1.digitaloceanspaces.com/test. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://---.sgp1.digitaloceanspaces.com/test. (Reason: CORS request did not succeed).

Failed to upload file NetworkingError: Network Failure

On my Spaces bucket, I set the following settings via the UI:

Origin: *
Allowed Methods: Get, Put, Delete, Post, Head
Allowed Headers: (empty)
Access Control Max Age: 15

I’ve been struggling with this for a few hours. I even waited an hour in case the CORS settings take a while to propagate.

As far as I can tell, this should be a working minimal example.

The issue is that the Access-Control-Allow-Origin header is missing from the prelight headers (HEAD request), even though it’s set to “*” via the UI.

How can I fix this? I’d really appreciate some help!

Submit an answer

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!