Upload and Download in amazon s3 bucket is very simple using AWS SDK.
First create a properties file which will store your amazon s3 credentials.
# Fill in your AWS Access Key ID and Secret Access Key # http://aws.amazon.com/security-credentials accessKey=your AccessKey secretKey=Your Secret keyNow for upload a file , create a PutObjectRequest specifying all the required attributes like this :
package com.test; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import com.amazonaws.auth.PropertiesCredentials; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3Client; import com.amazonaws.services.s3.model.ObjectMetadata; import com.amazonaws.services.s3.model.PutObjectRequest; import com.amazonaws.services.s3.model.PutObjectResult; public class UploadFile { public static void main(String[] args) throws IOException { String existingBucketName = "<your Bucket Name>"; String keyName = "mypic.JPG"; String filePath = "E://Pics//mypic.JPG"; String amazonFileUploadLocationOriginal=existingBucketName+"/Downloading the file is also very simple . Here is the sample file ."; AmazonS3 s3Client = new AmazonS3Client(new PropertiesCredentials(UploadFile.class.getResourceAsStream("AwsCredentials.properties"))); FileInputStream stream = new FileInputStream(filePath); ObjectMetadata objectMetadata = new ObjectMetadata(); PutObjectRequest putObjectRequest = new PutObjectRequest(amazonFileUploadLocationOriginal, keyName, stream, objectMetadata); PutObjectResult result = s3Client.putObject(putObjectRequest); System.out.println("Etag:" + result1.getETag() + "-->" + result); } }
package com.test; import java.io.FileOutputStream; import java.io.IOException; import java.util.List; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import com.amazonaws.auth.PropertiesCredentials; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3Client; import com.amazonaws.services.s3.model.Bucket; import com.amazonaws.services.s3.model.GetObjectRequest; import com.amazonaws.services.s3.model.ObjectListing; import com.amazonaws.services.s3.model.S3Object; import com.amazonaws.services.s3.model.S3ObjectInputStream; import com.amazonaws.services.s3.model.S3ObjectSummary; public class DownloadUploadedFile { public static void main(String[] args) throws IOException { String existingBucketName = "<your Bucket>"; String keyName = "Post Comments and suggestions !!/"+" "; AmazonS3 s3Client = new AmazonS3Client(new PropertiesCredentials( DownloadUploadedFile.class .getResourceAsStream("AwsCredentials.properties"))); GetObjectRequest request = new GetObjectRequest(existingBucketName, keyName); S3Object object = s3Client.getObject(request); S3ObjectInputStream objectContent = object.getObjectContent(); IOUtils.copy(objectContent, new FileOutputStream("D://upload//test.jpg")); } }