ブラウザから Amazon S3 へ直接ファイルアップロードするときの CORS 対応

Web ブラウザから Amazon S3 へ直接ファイルアップロードするときの CORS 対応をご紹介します。

AWS

背景 S3 へファイルアップロードで CORS エラー

Access to fetch at ‘https://xxx.s3-ap-northeast-1.amazonaws.com/xxx’ from origin ‘https://your-site.example.com’ 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.

というエラーが発生したので S3 の設定を変更して、無事解決したお話です。

Cross-Origin Resource Sharing (CORS) の設定例

[
    {
        "AllowedHeaders": [
            "Content-Type",
            "Origin"
        ],
        "AllowedMethods": [
            "GET",
            "PUT"
        ],
        "AllowedOrigins": [
            "https://your-site.example.com"
        ],
        "ExposeHeaders": [],
        "MaxAgeSeconds": 3000
    }
]

以上、Web ブラウザから Amazon S3 へ直接ファイルアップロードするときの CORS 対応した、現場からお送りしました。

参考情報