Getting started with Amazon S3 sdk with java

Put the sdk in your pom.xml of your maven project:
  1. <dependency>
  2.     <groupId>com.amazonaws</groupId>
  3.     <artifactId>aws-java-sdk</artifactId>
  4.     <version>1.9.13</version>
  5. </dependency>

Before running, make sure you setup API credentials properly.Follow the instruction here to do this :

Creating a directory:-
http://voidweb.com/2013/03/how-to-create-a-folder-programmatically-in-s3-using-amazon-aws-java-sdk/ has good examples for creating a directory
Uploading a file:-
Here is an for uploading a file which will be publicly accessible:
http://mohiplanet.blogspot.com/2014/11/aws-s3-multipart-file-upload-with.html
About content type:-
Note:- You have to select appropriate content types for each of your files. S3 SDK is not gonna do it automatically  for you.
Here is a sample that you can use during uploading with correct content type:-
  1. public ObjectMetadata generateCorrectContentTypeObjMetaFromKeyName(String key) throws InvalidContentTypeException {
  2. ObjectMetadata metadata = new ObjectMetadata();
  3. String contentType = getFileContentTypeFromFileName(key);
  4. if (contentType.length() == 0) {
  5. throw new InvalidContentTypeException();
  6. }
  7. LOG.log(Level.INFO, "Setting content type : " + contentType);
  8. metadata.setContentType(contentType);
  9. return metadata;
  10. }

Set content type according to your key name with:

  1. initRequest.setObjectMetadata(generateCorrectContentTypeObjMetaFromKeyName(keyName));

 Details and definition of getFileContentTypeFromFileName(key) are here:-
 http://mohiplanet.blogspot.com/2014/12/amazon-web-services-s3-api-java-client.html

More examples:-
https://github.com/aws/aws-sdk-java/tree/master/src/samples/AmazonS3

Command line tools for working fast:-
http://s3tools.org/s3cmd

No comments:

Post a Comment