阿里雲團隊努力不懈,力求將最新的技術內容更快地以您最熟悉的語言呈現。本文由簡體中文內容自動轉碼而成,過程無人工干預。阿里雲不保證此自動轉碼的準確性、完整性及時效性。因轉碼造成的任何內容錯誤及因此可能帶來的損失,阿里雲概不負責,敬請見諒。本文内容請以簡體中文版本為準。
全部產品
Search
文件中心

進度條

更新時間: Oct 19, 2018

進度條用於指示上傳或下載的進度。下面的代碼以ossClient.getObject方法為例,介紹如何使用進度條。

  1. static class GetObjectProgressListener implements ProgressListener {
  2. private long bytesRead = 0;
  3. private long totalBytes = -1;
  4. private boolean succeed = false;
  5. @Override
  6. public void progressChanged(ProgressEvent progressEvent) {
  7. long bytes = progressEvent.getBytes();
  8. ProgressEventType eventType = progressEvent.getEventType();
  9. switch (eventType) {
  10. case TRANSFER_STARTED_EVENT:
  11. System.out.println("Start to download......");
  12. break;
  13. case RESPONSE_CONTENT_LENGTH_EVENT:
  14. this.totalBytes = bytes;
  15. System.out.println(this.totalBytes + " bytes in total will be downloaded to a local file");
  16. break;
  17. case RESPONSE_BYTE_TRANSFER_EVENT:
  18. this.bytesRead += bytes;
  19. if (this.totalBytes != -1) {
  20. int percent = (int)(this.bytesRead * 100.0 / this.totalBytes);
  21. System.out.println(bytes + " bytes have been read at this time, download progress: " +
  22. percent + "%(" + this.bytesRead + "/" + this.totalBytes + ")");
  23. } else {
  24. System.out.println(bytes + " bytes have been read at this time, download ratio: unknown" +
  25. "(" + this.bytesRead + "/...)");
  26. }
  27. break;
  28. case TRANSFER_COMPLETED_EVENT:
  29. this.succeed = true;
  30. System.out.println("Succeed to download, " + this.bytesRead + " bytes have been transferred in total");
  31. break;
  32. case TRANSFER_FAILED_EVENT:
  33. System.out.println("Failed to download, " + this.bytesRead + " bytes have been transferred");
  34. break;
  35. default:
  36. break;
  37. }
  38. }
  39. public boolean isSucceed() {
  40. return succeed;
  41. }
  42. }
  43. public static void main(String[] args) {
  44. // Endpoint以杭州為例,其它Region請按實際情況填寫。
  45. String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
  46. // 阿里雲主帳號AccessKey擁有所有API的存取權限,風險很高。強烈建議您建立並使用RAM帳號進行API訪問或日常運維,請登入 https://ram.console.aliyun.com 建立RAM帳號。
  47. String accessKeyId = "<yourAccessKeyId>";
  48. String accessKeySecret = "<yourAccessKeySecret>";
  49. String bucketName = "<yourBucketName>";
  50. String objectName = "<yourObjectName>";
  51. OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
  52. try {
  53. // 帶進度條的下載。
  54. ossClient.getObject(new GetObjectRequest(bucketName, objectName).
  55. <GetObjectRequest>withProgressListener(new GetObjectProgressListener()),
  56. new File("<yourLocalFile>"));
  57. } catch (Exception e) {
  58. e.printStackTrace();
  59. }
  60. // 關閉OSSClient。
  61. ossClient.shutdown();
  62. }

ossClient.putObject、ossClient.getObject和ossClient.uploadPart方法支援進度條功能。ossClient.uploadFile和ossClient.downloadFile方法不支援進度條功能。

下載進度條的完整代碼請參見GitHub