使用 Amazon SDK 列出 Amazon S3 对象的网页
以下代码示例显示如何在网页中列出 Amazon S3 对象。
- JavaScript
-
- SDK for JavaScript (v3)
-
注意
在 GitHub 上查看更多内容。查找完整示例,学习如何在 Amazon 代码示例存储库
中进行设置和运行。 以下代码是对 Amazon 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 详细信息,请参阅《Amazon SDK for JavaScript API 参考》中的 ListObjects。
-
有关 Amazon SDK 开发人员指南和代码示例的完整列表,请参阅 将此服务与 Amazon SDK 结合使用。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。
创建预签名 URL
从多区域接入点中获取对象