Shaonline
Shaonline

Reputation: 1637

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

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

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

  2. 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 struggling with InputSteam and ObjectMetadata. I don't know what exactly is this for and how I can use it.

Upvotes: 8

Views: 27197

Answers (3)

koolhead17
koolhead17

Reputation: 1964

Alternatively you can use [minio client] java library

You can follow MakeBucket.java example to create a bucket & PutObject.java example to add an object.

Hope it help.

Upvotes: -1

Shawn Guo
Shawn Guo

Reputation: 3218

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.

Upvotes: 3

John Rotenstein
John Rotenstein

Reputation: 269111

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).

Upvotes: 19

Related Questions