user1042327
user1042327

Reputation: 387

S3 Iterate through Bucket/Folders/Files

I am iterating through S3 bucket using s3.listObjects but I am getting this error: { [UnexpectedParameter: Unexpected key 'Key' found in params] Below is the code I am using: exports.handler = function(event, context) {

var bucket = event.Records[0].s3.bucket.name;
var key = event.Records[0].s3.object.key;
var params = {
    Bucket: bucket,
    Key: key
};

console.log('bucket name ', bucket);
s3.getObject(params, function(err, data) {
    if (err) {
        console.log(err);

    } else {
        context.succeed(data.ContentType);
    }
});

s3.listObjects(params, function(err, data) {
    if (err) return console.log(err);

    params = {Bucket: 'bucketName'};

});
};

Can anyone please suggest what am I doing wrong here? Thanks

Upvotes: 1

Views: 8316

Answers (2)

plabon
plabon

Reputation: 71

if a is your bucket and images are under a/b/c folder . Then Just use Bucketname as "a" and add the path with image key.

Otherwise, just go to your aws service and find out your image key.

In my case images are under ctr/images/serviceImage.

var params = {

  Bucket: "ctr",//bucket name
  Delete: {
    Objects: [
      {
        Key: "images/ServiceImage/01c99e0c-f21e-4860-bf01-e7c79274b0ae.jpg"
      },
      {
        Key: "imgs/ServiceImage/0390cdf2-1989-43cd-8c93-77510dcd597e.jpg"
      }
    ],

    Quiet: false
  }

};

Upvotes: 0

peteb
peteb

Reputation: 19428

List objects doesn't take a key as a parameter since its wants to list all the keys in the bucket to you. Really its just looking for you to tell it which bucket to list the contents of. Additionally it does take some other parameters to help filter results and a max number of objects to return.

AWS.S3.listObjects Docs

// Acceptable Parameters as taken from the AWS.S3.listObjects Docs
var params = {
  Bucket: 'STRING_VALUE', /* required */
  Delimiter: 'STRING_VALUE',
  EncodingType: 'url',
  Marker: 'STRING_VALUE',
  MaxKeys: 0,
  Prefix: 'STRING_VALUE'
};

Essentially, the API is communicating to you that you're passing in an unnecessary parameter.

var params = { Bucket: bucket };
s3.listObjects(params, function(err, data) {
  if (err) return console.error(err);

  // data.Contents is the array of objects within the bucket
  console.log(data.Contents);
  return; 
});

Upvotes: 5

Related Questions