全部产品
阿里云办公

进度条

更新时间:2018-08-07 14:04:40

进度条用于指示上传或下载的进度。下面的代码以ossClient.putObject方法为例,介绍如何使用进度条。

  1. public class PutObjectProgressListener implements ProgressListener {
  2. private long bytesWritten = 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 upload......");
  12. break;
  13. case REQUEST_CONTENT_LENGTH_EVENT:
  14. this.totalBytes = bytes;
  15. System.out.println(this.totalBytes + " bytes in total will be uploaded to OSS");
  16. break;
  17. case REQUEST_BYTE_TRANSFER_EVENT:
  18. this.bytesWritten += bytes;
  19. if (this.totalBytes != -1) {
  20. int percent = (int)(this.bytesWritten * 100.0 / this.totalBytes);
  21. System.out.println(bytes + " bytes have been written at this time, upload progress: " + percent + "%(" + this.bytesWritten + "/" + this.totalBytes + ")");
  22. } else {
  23. System.out.println(bytes + " bytes have been written at this time, upload ratio: unknown" + "(" + this.bytesWritten + "/...)");
  24. }
  25. break;
  26. case TRANSFER_COMPLETED_EVENT:
  27. this.succeed = true;
  28. System.out.println("Succeed to upload, " + this.bytesWritten + " bytes have been transferred in total");
  29. break;
  30. case TRANSFER_FAILED_EVENT:
  31. System.out.println("Failed to upload, " + this.bytesWritten + " bytes have been transferred");
  32. break;
  33. default:
  34. break;
  35. }
  36. }
  37. public boolean isSucceed() {
  38. return succeed;
  39. }
  40. public static void main(String[] args) {
  41. // Endpoint以杭州为例,其它Region请按实际情况填写。
  42. String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
  43. // 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录 https://ram.console.aliyun.com 创建RAM账号。
  44. String accessKeyId = "<yourAccessKeyId>";
  45. String accessKeySecret = "<yourAccessKeySecret>";
  46. String bucketName = "<yourBucketName>";
  47. String objectName = "<yourObjectName>";
  48. // 创建OSSClient实例。
  49. OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
  50. try {
  51. // 带进度条的上传。
  52. ossClient.putObject(new PutObjectRequest(bucketName, objectName, new FileInputStream("<yourLocalFile>")).
  53. <PutObjectRequest>withProgressListener(new PutObjectProgressListener()));
  54. } catch (Exception e) {
  55. e.printStackTrace();
  56. }
  57. // 关闭OSSClient。
  58. ossClient.shutdown();
  59. }
  60. }

ossClient.putObject、ossClient.getObject和ossClient.uploadPart方法支持进度条功能。ossClient.uploadFile和ossClient.downloadFile方法不支持进度条功能。

上传进度条的完整代码请参见GitHub