首页 > 解决方案 > 仅从浏览器使用预签名 URL 上传时出现 AWS S3 CORS 错误

问题描述

我们有:

  1. 具有 CORS 设置的 S3 存储桶
[
    {
        "AllowedHeaders": [],
        "AllowedMethods": [
            "GET",
            "POST",
            "HEAD",
            "PUT",
            "DELETE"
        ],
        "AllowedOrigins": [
            "*"
        ],
        "ExposeHeaders": [
            "Authorization"
        ]
    }
]
  1. 预签名 POST python 代码
return self._client.generate_presigned_post(
            bucket_name or self._bucket_name,
            str(self._s3_bucket_root / full_path),
            Fields={
                'ACL': 'public-read'
            },
            Conditions=[{
                'ACL': 'public-read'
            }],
            ExpiresIn=ttl or self._default_s3_file_ttl
        )
  1. 反应我们得到错误的部分
                Object.keys(signature).forEach((key) => {
                    formData.append(key, signature[key]);
                })
                formData.append('files', file, file.filename);
                console.log('pureApolloClient.mutate // formData', formData);
                
                axios.post(
                    url,
                    formData,
                    {
                        headers: {'Content-Type': 'application/octet-stream'}
                    }
                );
  1. Firefox:http://localhost:3000控制台错误
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://hr-eco-bucket.s3.amazonaws.com/. (Reason: CORS request did not succeed).

一个星期左右我不知道出了什么问题。CORS 设置为最大访问权限,我应该没有错误

UPD 1:使用预签名 URL 上传与 python 测试完美配合

    signature = uploader.generate_presigned_url(fv.id, submission_uuid, submission_filename)

    resp = requests.post(
        signature['url'],
        data=signature['fields'],
        files={'file': (submission_filename, file_content)}
    )
    pdb.set_trace()
    assert resp.status_code == 204

    file_resp = requests.get(
        f'https://hr-eco-bucket.s3.eu-central-1.amazonaws.com/client-upload/vacancy/{fv.id}/submission/{submission_uuid}/{submission_filename}'
    )
    assert file_resp.content == file_content

UPD 2:我不确定这些屏幕截图有什么帮助。

CORS 错误

POST 标头

标签: amazon-web-servicesamazon-s3corsboto3pre-signed-url

解决方案


关闭 AWS 并尝试其他云解决方案。如果存在无法通过文档或指南明确解决的错误,则不应使用该服务。

UPD:说起来真的很难过,但我已经尝试过 GCP Storage,它确实有效。不用头疼,我刚刚设置了 CORS 标头,设置了存储桶策略以及上面的所有代码库和设置,除了 AWS 之外,与 GCP 配合得很好。我希望这将是另一个答案——我无法相信 S3 无法以简单的方式与 CORS 一起工作。


推荐阅读