首页 > 解决方案 > 如何通过为存储桶添加前缀来分区放大 S3 存储

问题描述

首先,我想在我的放大项目中设置多个 S3 存储。
但这暂时是不允许的(amplify-cli 向我展示Amazon S3 storage was already added to your project.

我通过创建分区为我的用例找到了可能的解决方案。
这在下面的链接中提到。

https://github.com/aws-amplify/amplify-cli/issues/1923#issuecomment-516508923

这说如下。

As a best practice, the Amplify Framwork allows you to have multiple prefixes in the bucket as a best practice instead of having multiple buckets.
You could partition your bucket by prefixes like the following:
`mybucket/partition1` and `mybucket/partition2` which can potentially have different auth policies and lambda triggers.

但它没有解释如何设置分区以及如何使用它。
那么,任何人都可以解释如何做到这一点?

标签: amazon-s3aws-amplify

解决方案


在文件夹 amplify/backend/storage/s3-cloudformation-template.json 中,您可以为新前缀添加新策略,该前缀将是 s3 存储桶中的文件夹名称

        "S3AuthStorage1Policy": {
            "DependsOn": [
                "S3Bucket"
            ],
            "Condition": "CreateAuthStorage1",
            "Type": "AWS::IAM::Policy",
            "Properties": {
                "PolicyName": {
                    "Ref": "s3Storage1Policy"
                },
                "Roles": [
                    {
                        "Ref": "authRoleName"
                    }
                ],
                "PolicyDocument": {
                    "Version": "2012-10-17",
                    "Statement": [
                        {
                            "Effect": "Allow",
                            "Action": {
                                "Fn::Split" : [ "," , {
                                    "Ref": "s3PermissionsAuthenticatedStorage1"
                                } ] 
                            },
                            "Resource": [
                                {
                                    "Fn::Join": [
                                        "",
                                        [
                                            "arn:aws:s3:::",
                                            {
                                                "Ref": "S3Bucket"
                                            },
                                            "/storage1/*"
                                        ]
                                    ]
                                }
                            ]
                        }
                    ]
                }
            }
        },

https://docs.amplify.aws/lib/storage/getting-started/q/platform/js#using-amazon-s3 https://github.com/aws-amplify/amplify-js/issues/332#issuecomment -602606514

现在您可以使用例如自定义前缀“storage1”将您的文件存储在 storage1 文件夹中。

Storage.put("storageTest.png", file, {
  contentType: "image/png",
  level: 'public',
  customPrefix: {
    public: "storage1/"
  }
})
  .then(result => console.log(result))
  .catch(err => console.log(err));

};

对另一个前缀(在此示例中为存储 2)执行相同操作,而不是将来自另一个用例的文件存储在另一个文件夹中。

具有两个自定义前缀的 s3 存储桶


推荐阅读