简体   繁体   English

列出AWS S3存储桶中的所有对象

[英]List all objects in AWS S3 bucket

I am trying to figure out how to list all the objects from an AWS S3 bucket in Swift. 我试图找出如何在Swift中列出AWS S3存储桶中的所有对象。 I can't seem to find the information anywhere on the internet, but maybe I didn't look hard enough. 我似乎无法在互联网上找到任何信息,但也许我看起来不够努力。 If anyone could refer me to the code that will allow me to do this that would be great. 如果有人可以推荐我的代码,这将允许我做这将是伟大的。

Don't know if you still need it but here you go: 不知道你是否仍然需要它但是你去了:

let credentialsProvider = AWSStaticCredentialsProvider(accessKey: "ACCESS KEY", secretKey: "SECRET KEY")
    let configuration = AWSServiceConfiguration(region: .USWest2, credentialsProvider: credentialsProvider)
    AWSS3.registerS3WithConfiguration(configuration, forKey: "defaultKey")
    let s3 = AWSS3.S3ForKey("defaultKey")

    let listRequest: AWSS3ListObjectsRequest = AWSS3ListObjectsRequest()
    listRequest.bucket = "BUCKET"

    s3.listObjects(listRequest).continueWithBlock { (task) -> AnyObject? in
        print("call returned")
        let listObjectsOutput = task.result;
        for object in (listObjectsOutput?.contents)! {

            print(object.key)
        }

        return nil
    }

(Thanks to Daniel for reminding me not to use deprecated code) ;) (感谢Daniel提醒我不要使用弃用的代码);)

Jan-Dawid's answer is great - however, if you want your Bucket NOT to be publicly available to everyone and still get the object-list then you have to do some more stuff (especially in the AWS settings) for this to happen (see list of things you have to do below....). Jan-Dawid的答案很棒 - 但是,如果你想让你的Bucket不向所有人公开,并且仍然可以获得对象列表,那么你必须做更多的事情(特别是在AWS设置中)才能实现这一点(参见列表你必须在下面做的事情....)

Or in other words, how do you get all the objects listed in Swift having your bucket set to publicly restricted as shown in this image (ie NO public ACCESS) 或者换句话说,如何将您的存储桶设置为公开限制的Swift中列出的所有对象(如此图所示)(即无公共访问)

在此输入图像描述

There is a way you can do that in Swift without AWS user-login setup needed in your app: 有一种方法可以在Swift中完成,而无需在您的应用中使用AWS用户登录设置:

Create an iOS App or open the one you want your bucket-object list to appear: 创建iOS应用程序或打开要显示的存储桶对象列表:

Type the following code: 输入以下代码:

let myIdentityPoolId = "eu-central-1:368293ad-f278-35ae-2678-6d40d48de2g5"
let credentialsProvider:AWSCognitoCredentialsProvider = AWSCognitoCredentialsProvider(regionType: .YOUR_REGION, identityPoolId: myIdentityPoolId)
let configuration = AWSServiceConfiguration(region: .YOUR_REGION, credentialsProvider:credentialsProvider)
AWSServiceManager.default().defaultServiceConfiguration = configuration

AWSS3.register(with: configuration!, forKey: "defaultKey")
let s3 = AWSS3.s3(forKey: "defaultKey")

let listRequest: AWSS3ListObjectsRequest = AWSS3ListObjectsRequest()
listRequest.bucket = "YOUR_BUCKET_NAME"

s3.listObjects(listRequest).continueWith { (task) -> AnyObject? in
    for object in (task.result?.contents)! {
        print("Object key = \(object.key!)")
    }
    return nil
}

(of course, you need to do some cosmetics to handle the case where no results should appear - but I leave that up to you. (当然,你需要做一些化妆品来处理不应该出现任何结果的情况 - 但我把它留给你。

Do make sure you have AWSS3 imported: 确保您已导入AWSS3:

import AWSS3

After that, you need to do a whole set of steps inside the AWS Service pages in order for your code to really retrieve the desired bucket-objects list. 之后,您需要在AWS服务页面内执行一系列步骤,以便您的代码真正检索所需的存储桶对象列表。 Here is a step-by-step guidance : 以下是分步指导:

Roughly, do the following: 粗略地,执行以下操作:

  1. Create a S3 Bucket 创建一个S3 Bucket
  2. Add items to it (the objects you want to have listed) 添加项目(您要列出的对象)
  3. In the bucket Access-control turn off all read&write access (as in image above) 在存储桶中,访问控制关闭所有读写访问权限(如上图所示)
  4. Go to AWS Cognito main page and choose: Manage Federated Identities 转到AWS Cognito主页,然后选择:管理联合身份

(By the way, all these AWS main-pages can best be found going to the AWS-Services page and typing the words "Cognito" or "IAM" or "S3" into the search bar. These 3 are all you need) (顺便说一句,所有这些AWS主页最好找到AWS-Services页面,并在搜索栏中输入“Cognito”或“IAM”或“S3”字样。这些都是您需要的3个)

在此输入图像描述

But let's continue.... 但是让我们继续......

  1. Inside "Manage Federated Identities", create a new identity pool (ie provide a name - AND DON'T FORGET TO TAG "Enable access to unauthenticated identities" (you can view the details and leave them unchanged) -> Press Allow! 在“管理联合身份”中,创建一个新的identity pool (即提供一个名称 - 并且不要忘记标记“启用对未经身份验证的身份的访问”(您可以查看详细信息并保持不变) - >按允许!

  2. Little EXTRA: In case you mess anything up and want to restart: There is a slight chance that the above step-Nr.6 does not work a second time with the same name. Little EXTRA:如果你搞砸了什么并且想要重新启动:上面的步骤Nr.6有可能第二次使用相同的名称。 In that case, I recommend going to the "IAM" main page and there, also delete the 2 roles connected to your identity pool (ie under Roles in IAM-main-page). 在这种情况下,我建议转到“IAM”主页,同时删除连接到您的身份池的2个角色(即在IAM-main-page中的Roles下)。 After the deletion of the roles, you can restart creating an identity-pool!) 删除角色后,可以重新开始创建标识池!)

  3. A second little EXTRA: Througout all we do right here, please make sure that all your AWS-main-service pages are within the same region !!! 第二个小额外的东西:我们在这里做的就是,请确保您所有的AWS主服务页面都在同一个区域! (normaly the AWS-webpages start with something like https://eu-central-1 . or https://us-west2 . etc. Make sure they are consistent throughout ! (通常情况下,AWS网页以https:// eu-central-1https:// us-west2开头 。确保它们始终保持一致!

But let's continue: 但是让我们继续:

  1. After identity-pool creation you should get an id for it (ie something like: eu-central-1:368293ad-f278-35ae-2678-6d40d48de2g5 (make sure you keep note of this id) 创建身份池后,你应该得到一个id(例如: eu-central-1:368293ad-f278-35ae-2678-6d40d48de2g5 (确保你记下这个id)

  2. Inside the "IAM"-main page, under the Roles menu, you find 2 roles (that were created by step-5-8) - click on the Unauth one of the two (you see there is an Auth and and Unauth one) 在“IAM”主页面内,在“角色”菜单下,您可以找到2个角色(由步骤5-8创建) - 单击Unauth中的一个(您看到有一个Auth和Unauth)

  3. Once the Unauth is clicked you get to the Summary page: There please keep note of the Role ARN (something like arn:aws:iam::274937169435:role/Cognito_YOURIDPOOLNAMEUnauth_Role ) 单击Unauth后,您将进入“摘要”页面:请注意角色ARN(类似于arn:aws:iam::274937169435:role/Cognito_YOURIDPOOLNAMEUnauth_Role

  4. Having the id's in hand you kept, go to the AWS-Policy-Generator page. 掌握了ID,请转到AWS-Policy-Generator页面。

  5. There, start filling you the Policy-Generator Form: 在那里,开始填写政策生成者表格:

    12a. 12A。 Select S3 Bucket Policy as the type 选择S3 Bucket Policy作为类型

    12b. 12B。 Chose Effect Allow 选择效果Allow

    12c. 12C。 In the prinicpal-field, paste the Role-ARN you obtained in Step-10 (something like arn:aws:iam::274937169435:role/Cognito_YOURIDPOOLNAMEUnauth_Role ) 在prinicpal-field中,粘贴你在Step-10中获得的Role-ARN(类似于arn:aws:iam::274937169435:role/Cognito_YOURIDPOOLNAMEUnauth_Role

    12d. 12D。 Amazon Service field should be Amazon S3 (leave tag deselected) 亚马逊服务字段应为Amazon S3 (取消选择保留标记)

    12e. 12E。 Actions should be ListObjects (or ListBuckets depending of what you want to do...) 动作应该是ListObjects (或ListBuckets取决于你想做什么......)

    12f. 12F。 The Amazon Resource Name (ARN) should be arn:aws:s3:::YOUR_BUCKET_NAME (if you want all files from your bucket eventually listed in Swift, then leave the blank> 亚马逊资源名称(ARN)应该是arn:aws:s3:::YOUR_BUCKET_NAME (如果您希望您的存储桶中的所有文件最终都在Swift中列出,那么请留空>

    12g. 12克。 Press Add statement button 按添加语句按钮

    12h. 12小时。 Press Create Policy button (that should generate a JSON-file) 按Create Policy按钮(应生成JSON文件)

Something like that: 像这样的东西:

{
  "Id": "Policy2846208763429",
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "Stmt98475983711245435",
      "Action": [
        "s3:ListBucket"
      ],
      "Effect": "Allow",
      "Resource": "arn:aws:s3:::YOUR_BUCKET_NAME",
      "Principal": {
        "AWS": [
          "arn:aws:iam::274937169435:role/Cognito_YOURIDPOOLNAMEUnauth_Role"
        ]
      }
    }
  ]
}
  1. With this Policy JSON-file in hand, go back to your "S3" bucket main page 有了这个Policy JSON文件,请返回“S3”存储桶主页

  2. Inside "S3" main page, go under --> "Persmissions" and press the tab "Bucket Policy" 在“S3”主页面下,转到 - >“Persmissions”,然后按“Bucket Policy”选项卡

  3. Replace anything written inside the Bucket Policy tab's editor window - and paste your Policy-JSON File (from Step 12h. into it) 替换Bucket Policy选项卡编辑器窗口中写入的任何内容 - 并粘贴Policy-JSON文件(从步骤12h开始)。

  4. After pasing the JSON make sure you press "Save" 在设置JSON之后,请确保按“保存”

---> HERE WE GO !! --->这里我们去!! THE SWFIT CODE SHOULD NOW RETRIEVE ALL BUCKET FILES IN THE RETURN TASK ANSWER !!!!! SWFIT代码现在应该在返回任务中回收所有桶文件!!!!!

  1. Optional: If you need any other AWS Services inside your iOS App, it is recommended that you use the following entry inside your info.plist file (providing the correct identity-pool id and region) 可选:如果您的iOS应用程序中需要任何其他AWS服务,建议您在info.plist文件中使用以下条目(提供正确的标识池ID和区域)

Step Nr17 is not really necessary if you only want to fetch the object list of your bucket. 如果您只想获取存储桶的对象列表,则不需要步骤Nr17。

    <key>AWS</key>
    <dict>
        <key>CredentialsProvider</key>
        <dict>
            <key>CognitoIdentity</key>
            <dict>
                <key>Default</key>
                <dict>
                    <key>PoolId</key>
                    <string>eu-central-1:368293ad-f278-35ae-2678-6d40d48de2g5</string>
                    <key>Region</key>
                    <string>eu-central-1</string>
                </dict>
            </dict>
        </dict>
        <key>S3TransferUtility</key>
        <dict>
            <key>Default</key>
            <dict>
                <key>Region</key>
                <string>eu-central-1</string>
            </dict>
        </dict>
    </dict>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM