使用 AWS SDK 列出 Amazon S3 物件的網頁 - AWSSDK 程式碼範例

AWS文件 AWS SDK 範例 GitHub 存放庫中提供了更多 SDK 範例

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

使用 AWS SDK 列出 Amazon S3 物件的網頁

下列程式碼範例顯示如何在網頁中列出 Amazon S3 物件。

JavaScript
適用於 JavaScript (v3) 的開發套件
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

下面的代碼是叫用 AWS SDK 的相關 React 元件。可以在前面 GitHub 的鏈接中找到包含此組件的應用程序的可運行版本。

import { useEffect, useState } from "react"; import { ListObjectsCommand, ListObjectsCommandOutput, S3Client, } from "@aws-sdk/client-s3"; import { fromCognitoIdentityPool } from "@aws-sdk/credential-providers"; import "./App.css"; function App() { const [objects, setObjects] = useState< Required<ListObjectsCommandOutput>["Contents"] >([]); useEffect(() => { const client = new S3Client({ region: "us-east-1", // Unless you have a public bucket, you'll need access to a private bucket. // One way to do this is to create an Amazon Cognito identity pool, attach a role to the pool, // and grant the role access to the 's3:GetObject' action. // // You'll also need to configure the CORS settings on the bucket to allow traffic from // this example site. Here's an example configuration that allows all origins. Don't // do this in production. //[ // { // "AllowedHeaders": ["*"], // "AllowedMethods": ["GET"], // "AllowedOrigins": ["*"], // "ExposeHeaders": [], // }, //] // credentials: fromCognitoIdentityPool({ clientConfig: { region: "us-east-1" }, identityPoolId: "<YOUR_IDENTITY_POOL_ID>", }), }); const command = new ListObjectsCommand({ Bucket: "bucket-name" }); client.send(command).then(({ Contents }) => setObjects(Contents || [])); }, []); return ( <div className="App"> {objects.map((o) => ( <div key={o.ETag}>{o.Key}</div> ))} </div> ); } export default App;
  • 如需 API 詳細資訊,請參閱 AWS SDK for JavaScriptAPI 參考ListObjects中的。