Java進度條
更新時間:
進度條用于指示上傳或下載文件的進度。本文以ossClient.putObject方法為例,介紹如何使用進度條。
注意事項
本文以華東1(杭州)外網(wǎng)Endpoint為例。如果您希望通過與OSS同地域的其他阿里云產(chǎn)品訪問OSS,請使用內網(wǎng)Endpoint。關于OSS支持的Region與Endpoint的對應關系,請參見OSS訪問域名、數(shù)據(jù)中心、開放端口。
本文以從環(huán)境變量讀取訪問憑證為例。如何配置訪問憑證,請參見Java配置訪問憑證。
本文以OSS域名新建OSSClient為例。如果您希望通過自定義域名、STS等方式新建OSSClient,請參見新建OSSClient。
示例代碼
以下代碼用于演示通過ossClient.putObject上傳文件時使用進度條的方法:
說明
ossClient.putObject、ossClient.getObject、ossClient.uploadPart、ossClient.uploadFile以及ossClient.downloadFile方法均支持進度條功能,使用方法與ossClient.putObject類似。
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
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;
// 使用進度條,需要實現(xiàn)ProgressListener方法
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 {
// Endpoint以華東1(杭州)為例,其它Region請按實際情況填寫。
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// 從環(huán)境變量中獲取訪問憑證。運行本代碼示例之前,請確保已設置環(huán)境變量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// 填寫B(tài)ucket名稱,例如examplebucket。
String bucketName = "examplebucket";
// 填寫Object完整路徑,完整路徑中不能包含Bucket名稱。例如exampledir/exampleobject.txt。
String objectName = "exampledir/exampleobject.txt";
// 填寫本地文件的完整路徑,例如D:\\localpath\\examplefile.txt。
String pathName = "D:\\localpath\\examplefile.txt";
// 填寫B(tài)ucket所在地域。以華東1(杭州)為例,Region填寫為cn-hangzhou。
String region = "cn-hangzhou";
// 創(chuàng)建OSSClient實例。
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// 上傳文件的同時指定進度條參數(shù)。此處PutObjectProgressListenerDemo為調用類的類名,請在實際使用時替換為相應的類名。
ossClient.putObject(new PutObjectRequest(bucketName,objectName, new File(pathName)).
<PutObjectRequest>withProgressListener(new PutObjectProgressListenerDemo()));
// 下載文件的同時指定進度條參數(shù)。此處GetObjectProgressListenerDemo為調用類的類名,請在實際使用時替換為相應的類名。
// ossClient.getObject(new GetObjectRequest(bucketName,objectName).
// <GetObjectRequest>withProgressListener(new GetObjectProgressListenerDemo()));
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
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("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
System.out.println("Error Message:" + ce.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
public boolean isSucceed() {
return succeed;
}
// 使用進度條需要您重寫回調方法,以下僅為參考示例。
@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;
}
}
}
相關文檔
關于上傳文件時進度條使用方法的完整示例代碼,請參見GitHub。
文檔內容是否對您有幫助?