AWS文件 AWS SDK 範例 GitHub 存放庫中提供了更多 SDK 範例
本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
適用於使用 AWS SDK 的 Amazon S3 程式碼範例
下列程式碼範例說明如何搭配AWS軟體開發套件 (SDK) 使用 Amazon 簡易儲存服務 (Amazon S3)。
Actions 是大型程式的程式碼摘錄,必須在內容中執行。雖然動作會告訴您如何呼叫個別服務函數,但您可以在其相關情境和跨服務範例中查看內容中的動作。
案例是向您展示如何呼叫相同服務中的多個函數來完成特定任務的程式碼範例。
Cross-service examples (跨服務範例) 是跨多個 AWS 服務 執行的應用程式範例。
其他 資源
Amazon S3 使用者指南 — 有關 Amazon S3 的更多資訊。
Amazon S3 API 參考 — 所有可用的 Amazon S3 動作的詳細資訊。
AWS開發人員中心
— 您可以依類別或全文檢索搜尋篩選的程式碼範例。 AWSSDK 示例
— 具有首選語言的完整代碼的 GitHub 回購。包括設定和執行程式碼的指示。
開始使用
下列程式碼範例示範如何開始使用 Amazon S3。
- C++
-
- 適用於 C++ 的 SDK
-
注意
還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫
。 C MakeLists .txt 的 CMake 文件的代碼。
# Set the minimum required version of CMake for this project. cmake_minimum_required(VERSION 3.13) # Set the AWS service components used by this project. set(SERVICE_COMPONENTS s3) # Set this project's name. project("hello_s3") # Set the C++ standard to use to build this target. # At least C++ 11 is required for the AWS SDK for C++. set(CMAKE_CXX_STANDARD 11) # Use the MSVC variable to determine if this is a Windows build. set(WINDOWS_BUILD ${MSVC}) if (WINDOWS_BUILD) # Set the location where CMake can find the installed libraries for the AWS SDK. string(REPLACE ";" "/aws-cpp-sdk-all;" SYSTEM_MODULE_PATH "${CMAKE_SYSTEM_PREFIX_PATH}/aws-cpp-sdk-all") list(APPEND CMAKE_PREFIX_PATH ${SYSTEM_MODULE_PATH}) endif () # Find the AWS SDK for C++ package. find_package(AWSSDK REQUIRED COMPONENTS ${SERVICE_COMPONENTS}) if (WINDOWS_BUILD) # Copy relevant AWS SDK for C++ libraries into the current binary directory for running and debugging. # set(BIN_SUB_DIR "/Debug") # if you are building from the command line you may need to uncomment this # and set the proper subdirectory to the executables' location. AWSSDK_CPY_DYN_LIBS(SERVICE_COMPONENTS "" ${CMAKE_CURRENT_BINARY_DIR}${BIN_SUB_DIR}) endif () add_executable(${PROJECT_NAME} hello_s3.cpp) target_link_libraries(${PROJECT_NAME} ${AWSSDK_LINK_LIBRARIES})
hello_s3.cpp 來源檔案的程式碼。
#include <aws/core/Aws.h> #include <aws/s3/S3Client.h> #include <iostream> #include <aws/core/auth/AWSCredentialsProviderChain.h> using namespace Aws; using namespace Aws::Auth; /* * A "Hello S3" starter application which initializes an Amazon Simple Storage Service (Amazon S3) client * and lists the Amazon S3 buckets in the selected region. * * main function * * Usage: 'hello_s3' * */ int main(int argc, char **argv) { Aws::SDKOptions options; // Optionally change the log level for debugging. // options.loggingOptions.logLevel = Utils::Logging::LogLevel::Debug; Aws::InitAPI(options); // Should only be called once. int result = 0; { Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region (overrides config file). // clientConfig.region = "us-east-1"; // You don't normally have to test that you are authenticated. But the S3 service permits anonymous requests, thus the s3Client will return "success" and 0 buckets even if you are unauthenticated, which can be confusing to a new user. auto provider = Aws::MakeShared<DefaultAWSCredentialsProviderChain>("alloc-tag"); auto creds = provider->GetAWSCredentials(); if (creds.IsEmpty()) { std::cerr << "Failed authentication" << std::endl; } Aws::S3::S3Client s3Client(clientConfig); auto outcome = s3Client.ListBuckets(); if (!outcome.IsSuccess()) { std::cerr << "Failed with error: " << outcome.GetError() << std::endl; result = 1; } else { std::cout << "Found " << outcome.GetResult().GetBuckets().size() << " buckets\n"; for (auto &bucket: outcome.GetResult().GetBuckets()) { std::cout << bucket.GetName() << std::endl; } } } Aws::ShutdownAPI(options); // Should only be called once. return result; }
-
如需 API 詳細資訊,請參閱 AWS SDK for C++API 參考ListBuckets中的。
-
- Go
-
- SDK for Go V2
-
注意
還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫
。 package main import ( "context" "fmt" "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/service/s3" ) // main uses the AWS SDK for Go V2 to create an Amazon Simple Storage Service // (Amazon S3) client and list up to 10 buckets in your account. // This example uses the default settings specified in your shared credentials // and config files. func main() { sdkConfig, err := config.LoadDefaultConfig(context.TODO()) if err != nil { fmt.Println("Couldn't load default configuration. Have you set up your AWS account?") fmt.Println(err) return } s3Client := s3.NewFromConfig(sdkConfig) count := 10 fmt.Printf("Let's list up to %v buckets for your account.\n", count) result, err := s3Client.ListBuckets(context.TODO(), &s3.ListBucketsInput{}) if err != nil { fmt.Printf("Couldn't list buckets for your account. Here's why: %v\n", err) return } if len(result.Buckets) == 0 { fmt.Println("You don't have any buckets!") } else { if count > len(result.Buckets) { count = len(result.Buckets) } for _, bucket := range result.Buckets[:count] { fmt.Printf("\t%v\n", *bucket.Name) } } }
-
如需 API 詳細資訊,請參閱 AWS SDK for GoAPI 參考ListBuckets
中的。
-
- Java
-
- 適用於 Java 2.x 的 SDK
-
注意
還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫
。 import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.model.Bucket; import software.amazon.awssdk.services.s3.model.ListBucketsResponse; import software.amazon.awssdk.services.s3.model.S3Exception; import java.util.List; /** * 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 HelloS3 { public static void main(String[] args) { Region region = Region.US_EAST_1; S3Client s3 = S3Client.builder() .region(region) .build(); listBuckets(s3); } public static void listBuckets(S3Client s3) { try { ListBucketsResponse response = s3.listBuckets(); List<Bucket> bucketList = response.buckets(); bucketList.forEach(bucket -> { System.out.println("Bucket Name: " + bucket.name()); }); } catch (S3Exception e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }
-
如需 API 詳細資訊,請參閱 AWS SDK for Java 2.xAPI 參考ListBuckets中的。
-
- JavaScript
-
- 適用於 JavaScript (v3) 的開發套件
-
注意
還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫
。 import { ListBucketsCommand, S3Client } from "@aws-sdk/client-s3"; // When no region or credentials are provided, the SDK will use the // region and credentials from the local AWS config. const client = new S3Client({}); export const helloS3 = async () => { const command = new ListBucketsCommand({}); const { Buckets } = await client.send(command); console.log("Buckets: "); console.log(Buckets.map((bucket) => bucket.Name).join("\n")); return Buckets; };
-
如需 API 詳細資訊,請參閱 AWS SDK for JavaScriptAPI 參考ListBuckets中的。
-
- PHP
-
- 適用於 PHP 的開發套件
-
注意
還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫
。 use Aws\S3\S3Client; $client = new S3Client(['region' => 'us-west-2']); $results = $client->listBuckets(); var_dump($results);
-
如需 API 詳細資訊,請參閱 AWS SDK for PHPAPI 參考ListBuckets中的。
-
- Python
-
- 適用於 Python (Boto3) 的 SDK
-
注意
還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫
。 import boto3 def hello_s3(): """ Use the AWS SDK for Python (Boto3) to create an Amazon Simple Storage Service (Amazon S3) resource and list the buckets in your account. This example uses the default settings specified in your shared credentials and config files. """ s3_resource = boto3.resource("s3") print("Hello, Amazon S3! Let's list your buckets:") for bucket in s3_resource.buckets.all(): print(f"\t{bucket.name}") if __name__ == "__main__": hello_s3()
-
如需 API 的詳細資訊,請參閱AWS開發套件ListBuckets中的 Python (博托 3) API 參考。
-
程式碼範例
- 動作
- 將 CORS 規則新增至儲存貯體
- 新增儲存貯體的生命週期組態
- 新增儲存貯體政策
- 取消分段上傳
- 完成分段上傳
- 從一個儲存貯體複製物件至另一個儲存貯體:
- 建立多區域存取點
- 建立 儲存貯體
- 建立分段上傳
- 從儲存貯體刪除 CORS 規則
- 從儲存貯體刪除政策
- 刪除空的儲存貯體
- 刪除物件
- 刪除多個物件
- 刪除儲存貯體的生命週期組態
- 從儲存貯體刪除網站組態
- 判斷物件是否存在和內容類型
- 判斷儲存貯體是否存在
- 將物件下載至本機目錄
- Enable logging (啟用日誌記錄)
- 啟用通知
- 啟用傳輸加速
- 取得儲存貯體的 CORS 規則
- 從多區域存取點取得物件
- 取得儲存貯體的物件
- 從儲存貯體中取得物件 (如果其已修改的話)
- 取得儲存貯體的 ACL
- 取得物件的 ACL
- 取得儲存貯體的區域位置
- 取得儲存貯體的生命週期組態
- 取得儲存貯體的政策
- 取得儲存貯體網站組態
- 列出儲存貯體
- 列出進行中的分段上傳
- 列出儲存貯體中的物件版本
- 列出儲存貯體中的物件
- 復原封存的物件複本
- 設定儲存貯體新的 ACL
- 設定物件的 ACL
- 設定儲存貯體網站組態
- 使用 SDK 進行單元和整合測試
- 上傳分段上傳的單一部分
- 將物件上傳至儲存貯體
- 將目錄上傳至儲存貯體
- 案例
- 無伺服器範例
- 跨服務範例