LoginSignup
3
0

More than 1 year has passed since last update.

AWS SDK for JavaScript v3 で S3 バケットのオブジェクト一覧を取得する

Posted at

初めに

認証情報を持たないユーザーが、ブラウザから S3 バケット内のオブジェクトリストを取得する方法を書きます。

ID プールを作成する

「ID プールの管理」をクリックします。

1.png

「新しい ID プールの作成」をクリックします。

2.png

ID プール名を入力し、「認証されていない ID に対してアクセスを有効にする」にチェックを入れます。

3.png

設定はデフォルトのまま、「許可」をクリックします。

4.png

「ID プールの編集」をクリックします。

5.png

ID プールの ID、各種ロールはここで確認できます。

6.png

認証されていないロール(上図緑下線)に以下のポリシーを追加します。

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "s3:ListBucket",
                "s3:GetObject"
            ],
            "Resource": [
                "arn:aws:s3:::bucket_name",
                "arn:aws:s3:::bucket_name/*"
            ]
        }
    ]
}

実装

準備

npm install @aws-sdk/client-s3
npm install @aws-sdk/credential-providers

コード例

App.js
import { S3Client, ListObjectsV2Command } from '@aws-sdk/client-s3';
import { fromCognitoIdentityPool } from "@aws-sdk/credential-providers";

const ListObjectByBrowser = async props => {

  const client = new S3Client({
    region: REGION, // リージョン
    credentials: fromCognitoIdentityPool({
      clientConfig: { region: REGION }, // リージョン
      identityPoolId: POOL_ID, // プール ID
    })
  });

  const command = new ListObjectsV2Command({
    Bucket: BUCKET_NAME // バケット名
  });
  const response = await client.send(command);
  console.log(response.Contents.map(x => x.Key)); // ["memo.txt", "sample.png"]
}

参考記事

3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0