AWS SDK 1.x - S3 file download & upload

Upasana | August 23, 2022 | 3 min read | 216 views | AWS Tutorials


We will use Amazon AWS SDK 1.x to make file upload and download from S3 bucket using Spring Boot application.

For AWS SDK 2.x, follow the below article:

Gradle setup

You can create a Spring Boot starter template using https://start.spring.io/ and add the below dependencies for Amazon SDK 1.x version.

build.gradle
dependencies {
    compile group: 'com.amazonaws', name: 'aws-java-sdk-core', version: '1.11.693'
    compile group: 'com.amazonaws', name: 'aws-java-sdk-s3', version: '1.11.693'
}

You can find the latest version of AWS SDK 1.x here:

Creating Bean for AmazonS3 client

We will create a Bean for AmazonS3 client that will be used across the Spring Boot application. All we need to get is AccessKey and SecretKey for AWS S3.

S3Config.java
import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.*;
import com.amazonaws.util.IOUtils;

@Configuration
public class S3Config {

    @Value("${aws.s3.accessKey}")
    private String accessKey;

    @Value("${aws.s3.secretKey}")
    private String secretKey;

    @Bean(destroyMethod = "close")
    public AmazonS3 s3Client() {
        return new AmazonS3Client(new BasicAWSCredentials(accessKey, secretKey));
    }
}

Upload file to S3

Uploading file to S3 bucket is simple, we will use s3client.putObject() operation to upload an attachment, as shown in below code snippet.

Upload Attachment to S3 Bucket
class Scratch {
    public String uploadPatientReport(byte[] attachment, String keyName, String contentType) {
        try {
            final ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentType(contentType);
            objectMetadata.setContentLength(attachment.length);
            final PutObjectResult putObjectResult = s3client.putObject(
                    new PutObjectRequest(reportBucket, keyName, new ByteArrayInputStream(attachment), objectMetadata));
            logger.info("putObjectResult = " + putObjectResult);
        } catch (AmazonServiceException ase) {
            logger.error("Caught an AmazonServiceException, which " + "means your request made it "
                    + "to Amazon S3, but was rejected with an error response" + " for some reason.");
            logger.info("Error Message:    " + ase.getMessage());
            logger.info("HTTP Status Code: " + ase.getStatusCode());
            logger.info("AWS Error Code:   " + ase.getErrorCode());
            logger.info("Error Type:       " + ase.getErrorType());
            logger.info("Request ID:       " + ase.getRequestId());
            throw ase;
        } catch (AmazonClientException ace) {
            logger.error("Caught an AmazonClientException, which " + "means the client encountered "
                    + "an internal error while trying to " + "communicate with S3, "
                    + "such as not being able to access the network.");
            logger.info("Error Message: " + ace.getMessage());
            throw ace;
        }
    }
}

Generating S3 PreSigned URL

Many a times we need to share a PreSigned URL with others so that they can access the file without providing the authentication details. PreSigned URL have ana expiry period after which URL becomes invalid.

Generate PreSigned URL with S3 client
class Scratch {
    public String generatePresignedUrl(byte[] attachment, String key, String contentType) {
        try {
            Calendar cal = Calendar.getInstance();
            cal.add(Calendar.HOUR, 12);
            final URL presignedUrl = s3client.generatePresignedUrl(reportBucket, key, cal.getTime());
            logger.info("putObjectResult = " + putObjectResult);
            logger.info("presignedUrl = " + presignedUrl);
            return presignedUrl.toString();
        } catch (AmazonServiceException ase) {
            logger.error("Caught an AmazonServiceException, which " + "means your request made it "
                    + "to Amazon S3, but was rejected with an error response" + " for some reason.");
            logger.info("Error Message:    " + ase.getMessage());
            logger.info("HTTP Status Code: " + ase.getStatusCode());
            logger.info("AWS Error Code:   " + ase.getErrorCode());
            logger.info("Error Type:       " + ase.getErrorType());
            logger.info("Request ID:       " + ase.getRequestId());
            throw ase;
        } catch (AmazonClientException ace) {
            logger.error("Caught an AmazonClientException, which " + "means the client encountered "
                    + "an internal error while trying to " + "communicate with S3, "
                    + "such as not being able to access the network.");
            logger.info("Error Message: " + ace.getMessage());
            throw ace;
        }
    }
}

Download file from S3

Using s3client.getObject(bucket, key) we can retrieve the object from S3 bucket and save it in byte array in-memory.

Download file from S3 bucket
class Scratch {
    public byte[] getFile(String bucket, String key) {
        try {
            final S3Object s3Object = s3client.getObject(bucket, key);
            final byte[] bytes = IOUtils.toByteArray(s3Object.getObjectContent());
            return bytes;
        } catch (AmazonServiceException ase) {  // Non-Retryable failure
            logger.error("Caught an AmazonServiceException, which " + "means your request made it "
                    + "to Amazon S3, but was rejected with an error response" + " for some reason.", ase);
            throw ase;
        } catch (AmazonClientException ace) {   //Retryable failure
            logger.error("Caught an AmazonClientException, which " + "means the client encountered "
                    + "an internal error while trying to " + "communicate with S3, "
                    + "such as not being able to access the network.", ace);
            throw ace;
        }
    }
}

That’s all.


Top articles in this category:
  1. AWS SDK 2: SQS Object Operations using Spring Boot
  2. Python: Send event from AWS Lambda to AWS SQS

Recommended books for interview preparation:

Find more on this topic: