Home > Back-end >  How do I move files in a S3 bucket while keeping the folders and not deleting them?
How do I move files in a S3 bucket while keeping the folders and not deleting them?

Time:05-04

In S3, I have a folder A that only has 1 file.

I want to move that file to folder B, as in copy the file from A to B & then deleting it from A.

However, the CDK is also deleting the A folder when it deletes the file. I want to keep both folders.

Why is it deleting the folders and how can I tell the CDK not to?

CodePudding user response:

While you see folders in the AWS console, there are no real 'folders' in Amazon S3. They are just simulated based on the object key containing a folder prefix followed by a forward slash. For example, the presence of an object with a prefix of A/ represents a logical folder named A.

After deleting the only object left with the 'folder' in its object key, there are no more objects left with the ‘folder’ in their keys so the ‘folder’ also disappears along with the object.

You will have to recreate the 'folder' yourself.

Refer to the documentation on how to manually create folders i.e. what the ‘Create folder’ option in the AWS console does:

When you use the Amazon S3 console to create a folder, Amazon S3 creates a 0-byte object with a key that's set to the folder name that you provided. For example, if you create a folder named photos in your bucket, the Amazon S3 console creates a 0-byte object with the key photos/. The console creates this object to support the idea of folders.

The Amazon S3 console treats all objects that have a forward slash (/) character as the last (trailing) character in the key name as a folder (for example, examplekeyname/). You can't upload an object that has a key name with a trailing / character by using the Amazon S3 console. However, you can upload objects that are named with a trailing / with the Amazon S3 API by using the AWS CLI, AWS SDKs, or REST API.

  • Related