LVB
LVB

Reputation: 392

renaming file before uploading it in S3

So i have a bucket in S3, I read about push model event of S3 bucket and I know how to bind an AWS lambda to a putObject event on the bucket. My problem is I want to rename the file before it uploads to a bucket, for example: in my bucket named 'example' there's a file called 'toto.jpeg', so if a user upload another image with the same name it will override it and the lambda function will receive the information after it has been uploaded to the bucket. And I don't want to rename the file on the client. Is there any solution?

Upvotes: 2

Views: 6153

Answers (2)

Abdel Atencio
Abdel Atencio

Reputation: 56

The question here is are you using a Backend language as NodeJS or PHP ?

If not and you are using the AWS SDK for browser, you can do something like:

<input type="file" accept="image/*" onchange="handleName(this.files)" />
function handleName (files) {
    var file = files[0];
    if (file) {
      var getExtension = file.name.slice((file.name.lastIndexOf(".") - 1 >>> 0) + 2);
      var fName = shortid.generate() + '.' + getExtension;
    }
}

notice that I'm using shortid to generate an unique short id, see this post if you want to create your own implementation create uuid in js.

then you can just call your S3 uploader function in handleName() function, if you want to trigger and upload in a click event, give an id to your input and get the file using a classical DOM selector: document.getElementById('input').files[0];

hope this can give you an idea.

regards!

Upvotes: 1

Mark B
Mark B

Reputation: 200657

The only solution is to specify the name before the file is uploaded. In other words, you have to do this in the client software. A Lambda function can't help you in this case because it won't be fired until after the file is uploaded. If you are worried about duplicate names causing files to be overwritten, you should enable versioning on your S3 bucket.

Upvotes: 3

Related Questions