将 PutBucketCors 与 Amazon SDK 或命令行工具结合使用 - Amazon Simple Storage Service
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

PutBucketCors 与 Amazon SDK 或命令行工具结合使用

以下代码示例演示如何使用 PutBucketCors

.NET
Amazon SDK for .NET
注意

在 GitHub 上查看更多内容。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

/// <summary> /// Add CORS configuration to the Amazon S3 bucket. /// </summary> /// <param name="client">The initialized Amazon S3 client object used /// to apply the CORS configuration to an Amazon S3 bucket.</param> /// <param name="configuration">The CORS configuration to apply.</param> private static async Task PutCORSConfigurationAsync(AmazonS3Client client, CORSConfiguration configuration) { PutCORSConfigurationRequest request = new PutCORSConfigurationRequest() { BucketName = BucketName, Configuration = configuration, }; _ = await client.PutCORSConfigurationAsync(request); }
  • 有关 API 详细信息,请参阅《Amazon SDK for .NET API 参考》中的 PutBucketCors

CLI
Amazon CLI

以下示例启用来自 www.example.comPUTPOSTDELETE 请求,并启用来自任何域的 GET 请求:

aws s3api put-bucket-cors --bucket MyBucket --cors-configuration file://cors.json cors.json: { "CORSRules": [ { "AllowedOrigins": ["http://www.example.com"], "AllowedHeaders": ["*"], "AllowedMethods": ["PUT", "POST", "DELETE"], "MaxAgeSeconds": 3000, "ExposeHeaders": ["x-amz-server-side-encryption"] }, { "AllowedOrigins": ["*"], "AllowedHeaders": ["Authorization"], "AllowedMethods": ["GET"], "MaxAgeSeconds": 3000 } ] }
  • 有关 API 详细信息,请参阅《Amazon CLI 命令参考》中的 PutBucketCors

Java
SDK for Java 2.x
注意

查看 GitHub,了解更多信息。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.S3Client; import java.util.ArrayList; import java.util.List; import software.amazon.awssdk.services.s3.model.GetBucketCorsRequest; import software.amazon.awssdk.services.s3.model.GetBucketCorsResponse; import software.amazon.awssdk.services.s3.model.DeleteBucketCorsRequest; import software.amazon.awssdk.services.s3.model.S3Exception; import software.amazon.awssdk.services.s3.model.CORSRule; import software.amazon.awssdk.services.s3.model.CORSConfiguration; import software.amazon.awssdk.services.s3.model.PutBucketCorsRequest; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class S3Cors { public static void main(String[] args) { final String usage = """ Usage: <bucketName> <accountId>\s Where: bucketName - The Amazon S3 bucket to upload an object into. accountId - The id of the account that owns the Amazon S3 bucket. """; if (args.length != 2) { System.out.println(usage); System.exit(1); } String bucketName = args[0]; String accountId = args[1]; Region region = Region.US_EAST_1; S3Client s3 = S3Client.builder() .region(region) .build(); setCorsInformation(s3, bucketName, accountId); getBucketCorsInformation(s3, bucketName, accountId); deleteBucketCorsInformation(s3, bucketName, accountId); s3.close(); } public static void deleteBucketCorsInformation(S3Client s3, String bucketName, String accountId) { try { DeleteBucketCorsRequest bucketCorsRequest = DeleteBucketCorsRequest.builder() .bucket(bucketName) .expectedBucketOwner(accountId) .build(); s3.deleteBucketCors(bucketCorsRequest); } catch (S3Exception e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } public static void getBucketCorsInformation(S3Client s3, String bucketName, String accountId) { try { GetBucketCorsRequest bucketCorsRequest = GetBucketCorsRequest.builder() .bucket(bucketName) .expectedBucketOwner(accountId) .build(); GetBucketCorsResponse corsResponse = s3.getBucketCors(bucketCorsRequest); List<CORSRule> corsRules = corsResponse.corsRules(); for (CORSRule rule : corsRules) { System.out.println("allowOrigins: " + rule.allowedOrigins()); System.out.println("AllowedMethod: " + rule.allowedMethods()); } } catch (S3Exception e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } public static void setCorsInformation(S3Client s3, String bucketName, String accountId) { List<String> allowMethods = new ArrayList<>(); allowMethods.add("PUT"); allowMethods.add("POST"); allowMethods.add("DELETE"); List<String> allowOrigins = new ArrayList<>(); allowOrigins.add("http://example.com"); try { // Define CORS rules. CORSRule corsRule = CORSRule.builder() .allowedMethods(allowMethods) .allowedOrigins(allowOrigins) .build(); List<CORSRule> corsRules = new ArrayList<>(); corsRules.add(corsRule); CORSConfiguration configuration = CORSConfiguration.builder() .corsRules(corsRules) .build(); PutBucketCorsRequest putBucketCorsRequest = PutBucketCorsRequest.builder() .bucket(bucketName) .corsConfiguration(configuration) .expectedBucketOwner(accountId) .build(); s3.putBucketCors(putBucketCorsRequest); } catch (S3Exception e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }
  • 有关 API 详细信息,请参阅《Amazon SDK for Java 2.x API 参考》中的 PutBucketCors

JavaScript
SDK for JavaScript (v3)
注意

在 GitHub 上查看更多内容。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

添加 CORS 规则。

import { PutBucketCorsCommand, S3Client } from "@aws-sdk/client-s3"; const client = new S3Client({}); // By default, Amazon S3 doesn't allow cross-origin requests. Use this command // to explicitly allow cross-origin requests. export const main = async () => { const command = new PutBucketCorsCommand({ Bucket: "test-bucket", CORSConfiguration: { CORSRules: [ { // Allow all headers to be sent to this bucket. AllowedHeaders: ["*"], // Allow only GET and PUT methods to be sent to this bucket. AllowedMethods: ["GET", "PUT"], // Allow only requests from the specified origin. AllowedOrigins: ["https://www.example.com"], // Allow the entity tag (ETag) header to be returned in the response. The ETag header // The entity tag represents a specific version of the object. The ETag reflects // changes only to the contents of an object, not its metadata. ExposeHeaders: ["ETag"], // How long the requesting browser should cache the preflight response. After // this time, the preflight request will have to be made again. MaxAgeSeconds: 3600, }, ], }, }); try { const response = await client.send(command); console.log(response); } catch (err) { console.error(err); } };
Python
SDK for Python(Boto3)
注意

查看 GitHub,了解更多信息。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

class BucketWrapper: """Encapsulates S3 bucket actions.""" def __init__(self, bucket): """ :param bucket: A Boto3 Bucket resource. This is a high-level resource in Boto3 that wraps bucket actions in a class-like structure. """ self.bucket = bucket self.name = bucket.name def put_cors(self, cors_rules): """ Apply CORS rules to the bucket. CORS rules specify the HTTP actions that are allowed from other domains. :param cors_rules: The CORS rules to apply. """ try: self.bucket.Cors().put(CORSConfiguration={"CORSRules": cors_rules}) logger.info( "Put CORS rules %s for bucket '%s'.", cors_rules, self.bucket.name ) except ClientError: logger.exception("Couldn't put CORS rules for bucket %s.", self.bucket.name) raise
  • 有关 API 详细信息,请参阅《Amazon SDK for Python (Boto3) API 参考》中的 PutBucketCors

Ruby
适用于 Ruby 的 SDK
注意

查看 GitHub,了解更多信息。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

require "aws-sdk-s3" # Wraps Amazon S3 bucket CORS configuration. class BucketCorsWrapper attr_reader :bucket_cors # @param bucket_cors [Aws::S3::BucketCors] A bucket CORS object configured with an existing bucket. def initialize(bucket_cors) @bucket_cors = bucket_cors end # Sets CORS rules on a bucket. # # @param allowed_methods [Array<String>] The types of HTTP requests to allow. # @param allowed_origins [Array<String>] The origins to allow. # @returns [Boolean] True if the CORS rules were set; otherwise, false. def set_cors(allowed_methods, allowed_origins) @bucket_cors.put( cors_configuration: { cors_rules: [ { allowed_methods: allowed_methods, allowed_origins: allowed_origins, allowed_headers: %w[*], max_age_seconds: 3600 } ] } ) true rescue Aws::Errors::ServiceError => e puts "Couldn't set CORS rules for #{@bucket_cors.bucket.name}. Here's why: #{e.message}" false end end
  • 有关 API 详细信息,请参阅《Amazon SDK for Ruby API 参考》中的 PutBucketCors

有关 Amazon SDK 开发人员指南和代码示例的完整列表,请参阅 将此服务与 Amazon SDK 结合使用。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。