获取目录文件列表

本SDK提供ListObjectsV2Command类用于获取目录文件列表。完整代码详见 GithubListObjectsV2Command调用的 S3 API 为 ListObjectsV2, 具体参见ListObjectsV2 API 文档

参数说明

  • Bucket: 文件所在的存储空间
  • MaxKeys: 请求返回的最大键数

示例

执行该示例前请确保配置文件的正确性
以下代码段需要在上下文中运行

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
function ListObjects() {
    const [bucketName, setBucketName] = useState("");
    const [maxKeys, setMaxKeys] = useState(10);  // 默认查找10个对象

    const [objects, setObjects] = useState([]);
    const [status, setStatus] = useState("");

    const handleListObjects = async () => {
        if (!bucketName) {
            setStatus("请提供有效的桶名称");
            return;
        }

        try {
            const command = new ListObjectsV2Command({
                Bucket: bucketName,
                MaxKeys: maxKeys > 0 ? maxKeys : 10,
            });

            let isTruncated = true;
            let continuationToken;
            let allObjects = [];

            while (isTruncated && allObjects.length < maxKeys) {
                const params = { ...command.input };
                if (continuationToken) {
                    params.ContinuationToken = continuationToken;
                }

                const response = await s3.send(new ListObjectsV2Command(params));
                if (response.Contents) {
                    allObjects = [...allObjects, ...response.Contents];
                }


                if (allObjects.length >= maxKeys) {
                    allObjects = allObjects.slice(0, maxKeys);
                    isTruncated = false;
                } else {
                    isTruncated = response.IsTruncated;
                    continuationToken = response.NextContinuationToken;
                }
            }

            setObjects(allObjects);
            setStatus(`成功查找到 ${allObjects.length} 个对象`);

        } catch (err) {
            console.error("查找对象错误:", err);
            setStatus("查找对象错误");
        }
    };