How to upload an object to S3 bucket using Java – AWS S3 PutObject

2 weeks ago Lalit Bhagtani 0

AWS S3 PutObject – In this tutorial, we will learn about how to upload an object to Amazon S3 bucket using java language.

Project Setup

Create a simple maven project in your favorite IDE and add below mentioned dependency in your pom.xml file.

<dependency>
  <groupId>com.amazonaws</groupId>
  <artifactId>aws-java-sdk-s3</artifactId>
  <version>1.11.533</version>
</dependency>

For latest version of aws library, check this page.

S3 Connection

Create an object of AmazonS3 ( com.amazonaws.services.s3.AmazonS3 ) class for sending a client request to S3. To get instance of this class, we will use AmazonS3ClientBuilder builder class. It requires three important parameters :- 

  1. Region :- It is a region where S3 table will be stored.
  2. ACCESS_KEY :- It is a access key for using S3. You can generate this key, using aws management console.
  3. SECRET_KEY :- It is a secret key of above mentioned access key.

Here is a code example :-

AmazonS3 s3 = AmazonS3ClientBuilder.standard()
				.withRegion(Regions.AP_SOUTH_1)
				.withCredentials(new AWSStaticCredentialsProvider
                                                    (new BasicAWSCredentials("ACCESS_KEY","SECRET_KEY")))
				.build();

Put Object

An AmazonS3.putObject method uploads a new Object to the specified Amazon S3 bucket. The specified bucket must be present in the Amazon S3 and the caller must have Permission.Write permission on the bucket.

The PutObjectRequest object can be used to create and send the client request to Amazon S3. A bucket name, object key, and file or input stream are only information required for uploading the object. This object can optionally upload an object metadata and can also apply a Canned ACL to the new object. Depending on whether a file or input stream is being uploaded, this request has slightly different behavior:-

Uploading File

  1. The AmazonS3 client automatically computes and validate a checksum of the file.
  2. AmazonS3 determines the correct content type and content disposition to use for the new object by using the file extension.

Uploading Input Stream

  1. The content length must be specified before data is uploaded to Amazon S3. If not provided, the library will have to buffer the contents of the input stream in order to calculate it.

Amazon S3 never stores partial objects, if an exception is thrown during an upload operation, the partial objects will get deleted.

Example

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.CannedAccessControlList;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.model.PutObjectResult;
import com.amazonaws.services.s3.model.StorageClass;

public class PutObject {

	public static void main(String[] args) {
		
		/* Create S3 Client Object */
		AmazonS3 s3 = AmazonS3ClientBuilder
				.standard()
				.withRegion(Regions.AP_SOUTH_1)
				.withCredentials(new AWSStaticCredentialsProvider(
                                     new BasicAWSCredentials("ACCESS_KEY","SECRET_KEY")))
				.build();		
		
		/* Set Bucket Name */
		String bucketName = "lb-aws-learning";
		
		InputStream inputStream = null;
				
		try {			
			
			/* Create File Object */
			File file = new File("C:/images/S3.png");
			
			/* Set Object Key */
			String objectKey = file.getName();
			
			/* Send Put Object Request */
			PutObjectResult result = s3.putObject(bucketName, objectKey, file);
			
			/* Second Way of Putting Object */
			
			/* Create File Object */
			file = new File("C:/images/S4.png");
			
			/* Create InputStream Object */
		    inputStream = new FileInputStream(file);
		    
		    /* Set Object Key */
		    objectKey = file.getName();
			
		    /* Create and Set Object Metadata */
		    ObjectMetadata metadata = new ObjectMetadata();
		    Map&lt;String,String&gt; map = new HashMap&lt;&gt;();
		    map.put("ImageType", "PNG");
		    
		    metadata.setUserMetadata(map);
		    
		    /* Set Content Length */
		    metadata.setContentLength(file.length());
		    
		    /* Create PutObjectRequest Object */
			PutObjectRequest request = new PutObjectRequest(bucketName, objectKey, inputStream, metadata);
			
			/* Set StorageClass as Standard Infrequent Access */
			request.setStorageClass(StorageClass.StandardInfrequentAccess);
			
			/* Set Canned ACL as BucketOwnerFullControl */
			request.setCannedAcl(CannedAccessControlList.BucketOwnerFullControl);
			
			/* Send Put Object Request */
		    result = s3.putObject(request);
        } catch (AmazonServiceException | IOException e) {
        	
            System.out.println(e.getMessage());            
        } finally {
        	
        	try {
				if (inputStream != null) {
					inputStream.close();				
				}
				if (s3 != null) {
					s3.shutdown();
				}
			} catch (IOException e) {
				System.out.println(e.getMessage());
			}        	
        }
	}
}

References :-

  1. PutObjectRequest Java Docs

That’s all for how to upload an object to Amazon S3 bucket using java language. (AWS S3 PutObject). If you liked it, please share your thoughts in comments section and share it with others too.