全部产品
弹性计算 会员服务 网络 安全 移动云 数加·大数据分析及展现 数加·大数据应用 管理与监控 云通信 阿里云办公 培训与认证 智能硬件
存储与CDN 数据库 域名与网站(万网) 应用服务 数加·人工智能 数加·大数据基础服务 互联网中间件 视频服务 开发者工具 解决方案 物联网 更多
对象存储 OSS

上传进度条

更新时间:2018-07-02 11:49:23

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

  1. static 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;z'z'z'za
  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. }
  41. public static void main(String[] args) {
  42. // Endpoint以杭州为例,其它Region请按实际情况填写。
  43. String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
  44. // 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录 https://ram.console.aliyun.com 创建RAM账号。
  45. String accessKeyId = "<yourAccessKeyId>";
  46. String accessKeySecret = "<yourAccessKeySecret>";
  47. String bucketName = "<yourBucketName>";
  48. String objectName = "<yourObjectName>";
  49. // 创建OSSClient实例。
  50. OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
  51. try {
  52. // 带进度条的上传。
  53. ossClient.putObject(new PutObjectRequest(bucketName, objectName, new FileInputStream("<yourLocalFile>")).
  54. <PutObjectRequest>withProgressListener(new PutObjectProgressListener()));
  55. } catch (Exception e) {
  56. e.printStackTrace();
  57. }
  58. // 关闭OSSClient。
  59. ossClient.shutdown();
  60. }

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

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

本文导读目录