Java SDK v2: Upload & Download from Spring

Harry · 14 Sep 2026 · 1 views
Advertisement
Advertisement

Add the dependency

<dependency>
    <groupId>software.amazon.awssdk</groupId>
    <artifactId>s3</artifactId>
    <version>2.25.11</version>
</dependency>

Credentials via the default chain

Never hard-code keys. The SDK automatically reads AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY from env vars, EC2 metadata, or ~/.aws/credentials:

export AWS_REGION=ap-south-1
export AWS_ACCESS_KEY_ID=AKIA...
export AWS_SECRET_ACCESS_KEY=...

Upload + download in Spring Boot

@Service
public class S3Service {
    private final S3Client s3; // built once at startup

    public void upload(byte[] data, String key) {
        s3.putObject(PutObjectRequest.builder()
                .bucket("groovygrails-books").key(key).build(),
            RequestBody.fromBytes(data));
    }

    public byte[] download(String key) {
        return s3.getObject(GetObjectRequest.builder()
                .bucket("groovygrails-books").key(key).build(),
            ResponseTransformer.toBytes()).asByteArray();
    }
}

Expose those via a @RestController — upload a book, fetch it back, then return the file straight in an HttpServletResponse — and you have a functional media/backup endpoint without touching your database.

Share this post:

Comments (0)

Please login or register to comment.