L’exemple de code Java suivant charge un fichier et utilise le ExecutionInterceptor
pour suivre la progression du chargement. Pour obtenir des instructions sur la création et le test d'un échantillon de travail, consultez Getting Started dans le guide du développeur AWS SDK pour Java 2.x.
import java.nio.file.Paths;
import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
import software.amazon.awssdk.core.async.AsyncRequestBody;
import software.amazon.awssdk.core.interceptor.Context;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.core.interceptor.ExecutionInterceptor;
import software.amazon.awssdk.services.s3.S3AsyncClient;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
public class TrackMPUProgressUsingHighLevelAPI {
static class ProgressListener implements ExecutionInterceptor {
private long transferredBytes = 0;
@Override
public void beforeTransmission(Context.BeforeTransmission context, ExecutionAttributes executionAttributes) {
if (context.httpRequest().firstMatchingHeader("Content-Length").isPresent()) {
String contentLength = context.httpRequest().firstMatchingHeader("Content-Length").get();
long partSize = Long.parseLong(contentLength);
transferredBytes += partSize;
System.out.println("Transferred bytes: " + transferredBytes);
}
}
}
public static void main(String[] args) throws Exception {
String existingBucketName = "*** Provide bucket name ***";
String keyName = "*** Provide object key ***";
String filePath = "*** file to upload ***";
S3AsyncClient s3Client = S3AsyncClient.builder()
.credentialsProvider(ProfileCredentialsProvider.create())
.overrideConfiguration(c -> c.addExecutionInterceptor(new ProgressListener()))
.build();
// For more advanced uploads, you can create a request object
// and supply additional request parameters (ex: progress listeners,
// canned ACLs, etc.)
PutObjectRequest request = PutObjectRequest.builder()
.bucket(existingBucketName)
.key(keyName)
.build();
AsyncRequestBody requestBody = AsyncRequestBody.fromFile(Paths.get(filePath));
// You can ask the upload for its progress, or you can
// add a ProgressListener to your request to receive notifications
// when bytes are transferred.
// S3AsyncClient processes all transfers asynchronously,
// so this call will return immediately.
var upload = s3Client.putObject(request, requestBody);
try {
// You can block and wait for the upload to finish
upload.join();
} catch (Exception exception) {
System.out.println("Unable to upload file, upload aborted.");
exception.printStackTrace();
} finally {
s3Client.close();
}
}
}