Connect to S4 with Java
Uses the AWS SDK for Java 2.x. Kotlin projects can use it directly too.
Prerequisites
- Create a bucket in the console;
- Create a sub-user and AccessKey, and grant the sub-user access to this bucket. A new sub-user has no permissions;
- Put the keys in environment variables instead of writing them in code:
export S4_ACCESS_KEY="Sub-user AccessKey"
export S4_SECRET_KEY="Sub-user SecretKey"Install
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>s3</artifactId>
<version>2.59.8</version>
</dependency>
<!-- Needed for multipart upload of large files -->
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>s3-transfer-manager</artifactId>
<version>2.59.8</version>
</dependency>implementation("software.amazon.awssdk:s3:2.59.8")
// Needed for multipart upload of large files
implementation("software.amazon.awssdk:s3-transfer-manager:2.59.8")The examples on this page were tested on Java 17. The required imports are:
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.time.Duration;
import java.util.*;
import software.amazon.awssdk.auth.credentials.*;
import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.core.sync.*;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.*;
import software.amazon.awssdk.services.s3.model.*;
import software.amazon.awssdk.services.s3.presigner.S3Presigner;
import software.amazon.awssdk.transfer.s3.S3TransferManager;
import software.amazon.awssdk.transfer.s3.model.*;
import software.amazon.awssdk.transfer.s3.progress.LoggingTransferListener;Connect to S4
static String BUCKET = "my-bucket";
static final URI ENDPOINT = URI.create("https://s3.bitiful.net");
static final Region REGION = Region.of("cn-east-1");
static final AwsCredentialsProvider CREDENTIALS = StaticCredentialsProvider.create(
AwsBasicCredentials.create(System.getenv("S4_ACCESS_KEY"), System.getenv("S4_SECRET_KEY")));
static final S3Client s3 = S3Client.builder()
.endpointOverride(ENDPOINT)
.region(REGION)
.credentialsProvider(CREDENTIALS)
.build();S3Client is thread-safe; create one per application. Versions 2.30 and later no longer require disabling Payload Signing or checksums.
Upload files
An object with the same name is overwritten directly. If ContentType is left empty, S4 detects it automatically.
// Upload a text string
s3.putObject(
PutObjectRequest.builder()
.bucket(BUCKET)
.key("docs/hello.txt")
.contentType("text/plain; charset=utf-8")
.build(),
RequestBody.fromString("你好,S4", StandardCharsets.UTF_8));
// Upload a local file, setting cache time and custom metadata
s3.putObject(
PutObjectRequest.builder()
.bucket(BUCKET)
.key("images/photo.jpg")
.contentType("image/jpeg")
.cacheControl("max-age=86400")
.metadata(Map.of("author", "bitiful"))
.build(),
RequestBody.fromFile(Path.of("photo.jpg")));Upload large files
Use multipart upload for files larger than 100 MB: parts can upload concurrently, and a failed part is the only one you need to retry. Each part is 5 MiB to 20 GiB, with up to 10000 parts.
S3AsyncClient async = S3AsyncClient.builder()
.endpointOverride(ENDPOINT)
.region(REGION)
.credentialsProvider(CREDENTIALS)
.multipartEnabled(true)
.multipartConfiguration(c -> c
.thresholdInBytes(16L * 1024 * 1024) // Split automatically above 16 MiB
.minimumPartSizeInBytes(16L * 1024 * 1024)) // At least 16 MiB per part
.build();
try (S3TransferManager tm = S3TransferManager.builder().s3Client(async).build()) {
FileUpload upload = tm.uploadFile(UploadFileRequest.builder()
.putObjectRequest(r -> r.bucket(BUCKET).key("videos/video.mp4").contentType("video/mp4"))
.source(Path.of("video.mp4"))
.addTransferListener(LoggingTransferListener.create()) // Print progress; requires an slf4j logging implementation
.build());
System.out.println(upload.completionFuture().join().response().eTag());
} finally {
async.close();
}Download files
Download private files with your secret key. To read only part of a file, use Range instead of downloading the whole file.
// Read as a string
String text = s3.getObjectAsBytes(r -> r.bucket(BUCKET).key("docs/hello.txt")).asUtf8String();
System.out.println(text);
// Save to a file
s3.getObject(
GetObjectRequest.builder().bucket(BUCKET).key("videos/video.mp4").build(),
ResponseTransformer.toFile(Path.of("video-copy.mp4")));
// Read only the first 1 KiB
var part = s3.getObjectAsBytes(r -> r.bucket(BUCKET).key("videos/video.mp4").range("bytes=0-1023"));
System.out.println(part.response().contentRange());List files
Each page returns 100 entries by default and 1000 at most; always use a paginator to page through results. Delimiter supports only /.
// List all objects under a prefix, paging automatically
s3.listObjectsV2Paginator(r -> r.bucket(BUCKET).prefix("images/"))
.contents()
.forEach(o -> System.out.println(o.key() + " " + o.size() + " " + o.lastModified()));
// List only the top-level directories
s3.listObjectsV2(r -> r.bucket(BUCKET).delimiter("/"))
.commonPrefixes()
.forEach(p -> System.out.println("Directory " + p.prefix()));Get file information
Retrieve metadata without downloading the content. You can also use this to check whether an object exists.
static boolean exists(String key) {
try {
s3.headObject(r -> r.bucket(BUCKET).key(key));
return true;
} catch (NoSuchKeyException e) {
return false;
}
}Copy and move
Copying is done server-side, so data does not pass through your machine. Move is an S4 extension: append ?move=true to CopySource. It only changes the location without copying data, regardless of file size. See Move and rename objects.
static void copy(String src, String dst) {
s3.copyObject(r -> r
.sourceBucket(BUCKET).sourceKey(src)
.destinationBucket(BUCKET).destinationKey(dst));
}// Move / rename: S4 extension, no data copied
// Pass the full string via copySource; you must URL-encode the object key yourself
@SuppressWarnings("deprecation")
static void move(String src, String dst) {
StringJoiner encoded = new StringJoiner("/");
for (String part : src.split("/", -1)) {
encoded.add(java.net.URLEncoder.encode(part, StandardCharsets.UTF_8).replace("+", "%20"));
}
s3.copyObject(CopyObjectRequest.builder()
.copySource(BUCKET + "/" + encoded + "?move=true")
.destinationBucket(BUCKET)
.destinationKey(dst)
.build());
}Delete files
Deleted objects cannot be recovered. A batch delete handles up to 1000 keys at a time; if you lack write permission on any one key, the whole batch returns 403.
// Delete one object
s3.deleteObject(r -> r.bucket(BUCKET).key("docs/hello.txt"));
// Batch delete, up to 1000 objects at a time
List<ObjectIdentifier> ids = List.of("images/a.jpg", "images/b.jpg").stream()
.map(k -> ObjectIdentifier.builder().key(k).build())
.toList();
DeleteObjectsResponse result = s3.deleteObjects(r -> r
.bucket(BUCKET)
.delete(d -> d.objects(ids).quiet(true)));
result.errors().forEach(e -> System.out.println(e.key() + " " + e.code() + " " + e.message()));Presigned URLs
A presigned URL embeds the authorization in the link, so the holder can upload or download without a secret key. It is valid for up to 7 days. If you sign Content-Type for an upload, the client must send exactly the same value.
String getUrl;
String putUrl;
try (S3Presigner presigner = S3Presigner.builder()
.endpointOverride(ENDPOINT).region(REGION).credentialsProvider(CREDENTIALS).build()) {
// Download URL, valid for 1 hour, with a specified file name
getUrl = presigner.presignGetObject(p -> p
.signatureDuration(Duration.ofHours(1))
.getObjectRequest(r -> r
.bucket(BUCKET)
.key("images/photo.jpg")
.responseContentDisposition("attachment; filename=\"photo.jpg\"")))
.url().toString();
// Upload URL, valid for 10 minutes; the client sends a PUT to it
putUrl = presigner.presignPutObject(p -> p
.signatureDuration(Duration.ofMinutes(10))
.putObjectRequest(r -> r.bucket(BUCKET).key("uploads/avatar.jpg")))
.url().toString();
}
System.out.println(getUrl);
System.out.println(putUrl);Presigned URLs with extension parameters
Extension parameters such as CoreIX processing parameters, rate limits, and request limits must be added before signing. Appending them after signing returns SignatureDoesNotMatch.
/** Generate a download URL with S4 extension parameters; they are included in the signature */
static String presignGetWith(String key, Map<String, String> params) {
var override = AwsRequestOverrideConfiguration.builder();
params.forEach(override::putRawQueryParameter);
try (S3Presigner presigner = S3Presigner.builder()
.endpointOverride(ENDPOINT).region(REGION).credentialsProvider(CREDENTIALS).build()) {
GetObjectRequest get = GetObjectRequest.builder()
.bucket(BUCKET).key(key)
.overrideConfiguration(override.build())
.build();
return presigner.presignGetObject(p -> p
.signatureDuration(Duration.ofHours(1))
.getObjectRequest(get)).url().toString();
}
}String url = presignGetWith("images/photo.jpg", Map.of(
"w", "500", // CoreIX: width 500 px
"fmt", "webp", // CoreIX: convert to WebP
"x-bitiful-limit-rate", "1048576", // Per-connection rate limit of 1 MiB/s
"x-bitiful-max-requests", "3")); // At most 3 accessesConditional writes
Conditional writes prevent concurrent overwrites. When the condition is not met, S4 returns 412. See Conditional requests.
try {
// Write only if the object does not exist, to prevent overwriting
s3.putObject(r -> r.bucket(BUCKET).key("locks/job").ifNoneMatch("*"), RequestBody.fromString("me"));
} catch (S3Exception e) {
if (e.statusCode() != 412) throw e;
System.out.println("Object already exists");
}Handle errors
For the meaning of each error code, see Error codes and troubleshooting. Rate limiting returns 429 TooManyRequest; catch it and retry with backoff.
try {
s3.getObjectAsBytes(r -> r.bucket(BUCKET).key("not-exists.txt"));
} catch (NoSuchKeyException e) {
System.out.println("Object does not exist");
} catch (S3Exception e) {
System.out.println(e.statusCode() + " " + e.awsErrorDetails().errorCode()
+ " " + e.awsErrorDetails().errorMessage() + " " + e.requestId());
} catch (SdkClientException e) {
System.out.println("Network error: " + e.getMessage());
}FAQ
How do I use it in Spring Boot
Declare S3Client and S3Presigner as @Beans and reuse them instead of creating them in every request.
Returns 403 AccessDenied
The sub-user has no permission on this bucket or directory. See Sub-user permissions. Creating and deleting buckets can only be done in the console.
Returns SignatureDoesNotMatch
The key was copied incorrectly, or the presigned URL was modified after signing. Extension parameters must be added before signing. See the checklist.
Download speed is low
Direct S4 connections have a per-connection rate limit. Download large files in segments over multiple threads, and use a CDN to serve visitors.
Related documentation
Full reference for request limits, rate limits, Simul-Transfer, and other parameters.
Checklists for 403, SignatureDoesNotMatch, and other issues.
Support status and differences for each operation.
Recommended practices for direct uploads from browsers and apps.