AWS API Gateway集成S3:如何列出指定文件夹下文件?
问题分析与解决方案
你遇到的The specified key does not exist错误,核心原因是当前的列表对象集成配置错误地让API Gateway尝试获取一个名为{folder}/{fileType}的S3对象,而非列出该前缀下的所有文件。S3没有这个键对应的对象,因此报错。
修正步骤
1. 调整S3列表集成的配置
需要将集成从"获取对象"模式改为"列出对象"模式,使用S3的ListObjectsV2操作,并传递正确的prefix参数:
// 修正后的S3列表对象集成 const s3IntegrationListObjects = new apigw.AwsIntegration({ service: 's3', integrationHttpMethod: 'GET', action: 'ListObjectsV2', // 指定S3的ListObjectsV2操作 options: { credentialsRole: executeRole, integrationResponses: [ { statusCode: '200', responseParameters: { 'method.response.header.Content-Type': "'application/xml'", }, }, { statusCode: '404', selectionPattern: '.*NoSuchBucket.*|.*NoSuchKey.*', }, ], requestParameters: { // 将路径参数拼接为S3前缀(结尾加斜杠避免匹配其他前缀) 'integration.request.querystring.prefix': "method.request.path.folder + '/' + method.request.path.fileType + '/'", 'integration.request.querystring.delimiter': "'/'", // 只返回当前层级的文件 'integration.request.path.bucket': `'${dataBucket.bucketName}'`, }, }, });
2. 修正API Gateway方法配置
确保方法的请求参数和响应参数匹配新的集成配置:
// 修正后的列表对象GET方法 fileTypeResource.addMethod('GET', s3IntegrationListObjects, { authorizationType: apigw.AuthorizationType.IAM, methodResponses: [ { statusCode: '200', responseParameters: { 'method.response.header.Content-Type': true, }, }, { statusCode: '404', }, ], requestParameters: { 'method.request.path.folder': true, 'method.request.path.fileType': true, }, });
3. 检查IAM角色权限
确保executeRole拥有S3桶的列表权限,而非仅获取对象权限:
// 给executeRole添加ListBucket权限 executeRole.addToPolicy(new iam.PolicyStatement({ actions: ['s3:ListBucket'], resources: [dataBucket.bucketArn], conditions: { StringLike: { 's3:prefix': ['*/*/*/'] // 匹配你的前缀结构,可按需调整 } } }));
关键说明
- S3的列表操作依赖
ListObjectsV2API,而非直接访问路径,因此需要通过action参数指定操作,而非路径。 prefix参数结尾必须加斜杠(/),否则会匹配所有以{folder}/{fileType}开头的键,比如{folder}/{fileType}OtherFile.txt。delimiter参数设为/可以确保只返回当前文件夹下的文件,不会递归返回子文件夹内容。
内容的提问来源于stack exchange,提问作者quartaela
相关产品推荐
相关产品推荐

