全部产品
Search
文档中心

Object Storage Service:Progress bar (Java SDK V1)

更新时间:Nov 26, 2025

Anda dapat menggunakan progress bar untuk menampilkan kemajuan unggah atau unduh objek. Topik ini menjelaskan cara menggunakan progress bar saat memanggil metode ossClient.putObject untuk mengunggah objek.

Catatan penggunaan

  • Topik ini menggunakan titik akhir publik wilayah China (Hangzhou). Untuk mengakses OSS dari layanan Alibaba Cloud lainnya di wilayah yang sama, gunakan titik akhir internal. Untuk informasi selengkapnya mengenai wilayah dan titik akhir yang didukung, lihat Regions and endpoints.

  • Kredensial akses pada topik ini diperoleh dari variabel lingkungan. Untuk informasi selengkapnya tentang cara mengonfigurasi kredensial akses, lihat Configure access credentials.

  • Pada topik ini, instans OSSClient dibuat menggunakan titik akhir OSS. Jika Anda ingin membuat instans OSSClient menggunakan nama domain kustom atau Security Token Service (STS), lihat Configuration examples for common scenarios.

Kode contoh

Kode berikut menunjukkan cara menggunakan progress bar saat memanggil metode ossClient.putObject untuk mengunggah objek.

Catatan

Metode-metode berikut mendukung progress bar: ossClient.putObject, ossClient.getObject, ossClient.uploadPart, ossClient.uploadFile, dan ossClient.downloadFile. Prosedur penerapan progress bar pada metode-metode tersebut sama dengan prosedur pada metode ossClient.putObject.

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
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;

// Gunakan metode ProgressListener untuk menggunakan progress bar.
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 {
        // Pada contoh ini, titik akhir wilayah China (Hangzhou) digunakan. Tentukan titik akhir aktual Anda.
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Peroleh kredensial akses dari variabel lingkungan. Sebelum menjalankan kode contoh, pastikan variabel lingkungan OSS_ACCESS_KEY_ID dan OSS_ACCESS_KEY_SECRET telah dikonfigurasi.
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Tentukan nama bucket. Contoh: examplebucket.
        String bucketName = "examplebucket";
        // Tentukan path lengkap objek. Jangan sertakan nama bucket dalam path lengkap. Contoh: exampledir\exampleobject.txt.
        String objectName = "exampledir/exampleobject.txt";
        // Tentukan path lengkap file lokal. Contoh: D:\\localpath\\examplefile.txt.
        String pathName = "D:\\localpath\\examplefile.txt";
        // Tentukan wilayah tempat bucket berada. Misalnya, jika bucket berada di wilayah China (Hangzhou), atur wilayah menjadi cn-hangzhou.
        String region = "cn-hangzhou";

        // Buat instans OSSClient.
        // Panggil metode shutdown untuk melepaskan sumber daya terkait ketika OSSClient tidak lagi digunakan.
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            // Tentukan parameter progress bar saat Anda mengunggah objek. Pada contoh ini, PutObjectProgressListenerDemo menentukan nama kelas yang ingin Anda panggil. Gantilah dengan nama kelas aktual.
            ossClient.putObject(new PutObjectRequest(bucketName,objectName, new File(pathName)).
                    <PutObjectRequest>withProgressListener(new PutObjectProgressListenerDemo()));
            // Tentukan parameter progress bar saat Anda mengunduh objek. Pada contoh ini, GetObjectProgressListenerDemo menentukan nama kelas yang ingin Anda panggil. Gantilah dengan nama kelas aktual.
//            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;
    }

    // Timpa metode callback untuk menggunakan progress bar. Kode contoh berikut memberikan ilustrasi:
    @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;
        }
    }
}

Referensi

Untuk informasi selengkapnya mengenai kode contoh lengkap progress bar dalam pengunggahan objek, kunjungi GitHub.