creating a folder/uploading a file in amazon S3 bucket using API

21,069

Solution 1

Yes, you can use PutObjectRequest(bucketName, keyName, file) to achive both task.

1, create S3 folder
With AWS S3 Java SDK , just add "/" at the end of the key name, it will create empty folder.

var folderKey =  key + "/"; //end the key name with "/"

Sample code:

final InputStream im = new InputStream() {
      @Override
      public int read() throws IOException {
        return -1;
      }
    };
    final ObjectMetadata om = new ObjectMetadata();
    om.setContentLength(0L);
    PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, im, om);
    s3.putObject(putObjectRequest);

2, Uploading file Just similar, you can get input stream from your local file.

Solution 2

You do not need to create a folder in Amazon S3. In fact, folders do not exist!

Rather, the Key (filename) contains the full path and the object name.

For example, if a file called cat.jpg is in the animals folder, then the Key (filename) is: animals/cat.jpg

Simply Put an object with that Key and the folder is automatically created. (Actually, this isn't true because there are no folders, but it's a nice simple way to imagine the concept.)

As to which function to use... always use the simplest one that meets your needs. Therefore, just use PutObjectRequest(bucketName, keyName, file).

Share:
21,069
Shaonline
Author by

Shaonline

Updated on July 09, 2022

Comments

  • Shaonline
    Shaonline almost 2 years

    I am a total newbie to amazon and java. I am trying two things here.

    1st - I am trying to create a folder in my Amazon S3 bucket that i have already created and have got the credentials for.

    2nd - I am trying to upload a file to this bucket.

    As per my understanding i can use putObjectRequest() method for acheiving both of my tasks.

    PutObjectRequest(bucketName, keyName, file) 
    

    for uploading a file.

    I am not sure if i should use this method

    PutObjectRequest(String bucketName, String key, InputStream input,
            ObjectMetadata metadata) 
    

    for just creating a folder. I am struggeling with InputSteam and ObjectMetadata. I don't know what exactly is this for and how can i use it.

    Any help would be greatly appreciated. :)