Implement a ProgressListener to track the progress of object uploads and downloads. This topic demonstrates progress tracking using ossClient.putObject.
Usage notes
The sample code uses the public endpoint for the China (Hangzhou) region. To access OSS from other Alibaba Cloud services in the same region, use an internal endpoint. For supported regions and endpoints, see OSS regions and endpoints.
The sample code reads credentials from environment variables. For configuration details, see Configure access credentials.
The sample code creates an
OSSClientinstance using an OSS endpoint. To create an instance with a custom domain name or Security Token Service (STS), see Configuration examples for common scenarios.
How it works
Implement the ProgressListener interface and override the progressChanged(ProgressEvent progressEvent) callback method. The SDK invokes this callback during a transfer with the following events, in order:
| Event | Triggered | Data available |
|---|---|---|
TRANSFER_STARTED_EVENT | Once, when the transfer begins | None |
REQUEST_CONTENT_LENGTH_EVENT | Once, with the total byte count | getBytes() returns total bytes |
REQUEST_BYTE_TRANSFER_EVENT | Multiple times throughout the transfer | getBytes() returns bytes transferred in this chunk |
TRANSFER_COMPLETED_EVENT | Once, on success | Cumulative bytes written available via bytesWritten |
TRANSFER_FAILED_EVENT | Once, on failure | Cumulative bytes written available via bytesWritten |
Note:totalBytesis-1if the content length is unknown. Handle this case to avoid division-by-zero errors when calculating the percentage.
Attach the listener to a request object using .withProgressListener(new YourProgressListener()). The following methods support progress tracking:
ossClient.putObjectossClient.getObjectossClient.uploadPartossClient.uploadFileossClient.downloadFile
The procedure is the same for all methods.
Sample code
The following example tracks upload progress using ossClient.putObject.
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.event.ProgressEvent;
import com.aliyun.oss.event.ProgressEventType;
import com.aliyun.oss.event.ProgressListener;
import com.aliyun.oss.model.PutObjectRequest;
import java.io.File;
// Implement ProgressListener to track upload progress.
public class PutObjectProgressListenerDemo implements ProgressListener {
private long bytesWritten = 0;
private long totalBytes = -1;
private boolean succeed = false;
public static void main(String[] args) throws Exception {
// Specify the endpoint for the China (Hangzhou) region. Replace with your actual endpoint.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Read credentials from environment variables OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Replace with your bucket name, object name, and local file path.
String bucketName = "examplebucket";
String objectName = "exampledir/exampleobject.txt";
String pathName = "D:\\localpath\\examplefile.txt";
String region = "cn-hangzhou";
// Build the OSSClient with V4 signature. Call shutdown() when done.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// Attach the progress listener to the upload request.
ossClient.putObject(new PutObjectRequest(bucketName, objectName, new File(pathName))
.<PutObjectRequest>withProgressListener(new PutObjectProgressListenerDemo()));
// To track a download instead, uncomment the following:
// ossClient.getObject(new GetObjectRequest(bucketName, objectName)
// .<GetObjectRequest>withProgressListener(new GetObjectProgressListenerDemo()));
} catch (OSSException oe) {
System.out.println("Request reached OSS but was rejected.");
System.out.println("Error Message: " + oe.getErrorMessage());
System.out.println("Error Code: " + oe.getErrorCode());
System.out.println("Request ID: " + oe.getRequestId());
System.out.println("Host ID: " + oe.getHostId());
} catch (ClientException ce) {
System.out.println("Client-side error — check network connectivity.");
System.out.println("Error Message: " + ce.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
public boolean isSucceed() {
return succeed;
}
// Override progressChanged to handle each transfer event.
@Override
public void progressChanged(ProgressEvent progressEvent) {
long bytes = progressEvent.getBytes();
ProgressEventType eventType = progressEvent.getEventType();
switch (eventType) {
case TRANSFER_STARTED_EVENT:
System.out.println("Start to upload......");
break;
case REQUEST_CONTENT_LENGTH_EVENT:
this.totalBytes = bytes;
System.out.println(this.totalBytes + " bytes in total will be uploaded to OSS");
break;
case REQUEST_BYTE_TRANSFER_EVENT:
this.bytesWritten += bytes;
if (this.totalBytes != -1) {
int percent = (int)(this.bytesWritten * 100.0 / this.totalBytes);
System.out.println(bytes + " bytes have been written at this time, upload progress: "
+ percent + "%(" + this.bytesWritten + "/" + this.totalBytes + ")");
} else {
System.out.println(bytes + " bytes have been written at this time, upload ratio: unknown"
+ "(" + this.bytesWritten + "/...)");
}
break;
case TRANSFER_COMPLETED_EVENT:
this.succeed = true;
System.out.println("Succeed to upload, " + this.bytesWritten + " bytes have been transferred in total");
break;
case TRANSFER_FAILED_EVENT:
System.out.println("Failed to upload, " + this.bytesWritten + " bytes have been transferred");
break;
default:
break;
}
}
}References
For the complete sample code, see GetProgressSample.java on GitHub.