全部产品
阿里云办公

进度条

更新时间:2018-07-18 22:30:44

进度条用于指示上传或下载的进度。下面的代码以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