如果您在使用 Amazon S3 存储桶时遇到了 CORS 问题,可以使用以下方法进行解决:
在 S3 存储桶的属性中,转到权限选项卡,然后单击编辑 CORS 配置。然后,将以下代码粘贴到 CORS 配置框中:
*
GET
3000
Authorization
Content-Type
Origin
上述代码将允许从任何来源访问存储桶,并添加了三个允许头部。
请注意,如果您使用的是自定义域名,则应将 AllowedOrigin 的值更改为您的自定义域名。
此外,在上传文件时,您需要包括适当的头部信息。以下是几个示例:
使用 JavaScript 进行上传:
const formData = new FormData();
formData.append('file', file);
fetch('https://your-bucket.s3.amazonaws.com', {
method: 'POST',
headers: {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'multipart/form-data'
},
body: formData
});
使用 Python 进行上传:
import boto3
s3 = boto3.client('s3')
with open("file.txt", "rb") as f:
s3.upload_fileobj(f, "your-bucket", "file.txt",
ExtraArgs={'ContentType': 'text/plain',
'ACL': 'public-read',
'Metadata': {'Content-Type': 'text/plain', 'ACL': 'public-read', 'Cache-Control': 'max-age=86400'}})
使用 PHP 进行上传:
$s3 = new Aws\S3\S3Client([
'version' => 'latest',
'region' => 'your-region',
'endpoint' => 'https://your-bucket.s3.amazonaws.com',
'use_path_style_endpoint' => true,
]);
$key = 'file.txt';
$result = $s3->putObject([
'Bucket' => 'your-bucket',
'Key' => $key,
'SourceFile'