Tous les produits
Search
Centre de documentation

Object Storage Service:Téléchargement multipart (Java SDK V1)

Dernière mise à jour :Aug 18, 2026

Object Storage Service (OSS) propose une fonctionnalité de téléchargement multipart pour les objets volumineux. Ce processus consiste à diviser un objet volumineux en parties plus petites, à les télécharger indépendamment, puis à appeler l'API CompleteMultipartUpload pour assembler les parties en un seul objet. Cette approche permet de reprendre les téléchargements interrompus.

Notes

  • Cette rubrique utilise le point de terminaison public de la région Chine (Hangzhou). Pour accéder à OSS depuis d'autres services Alibaba Cloud dans la même région, utilisez un point de terminaison interne. Pour obtenir la liste des régions et des points de terminaison pris en charge, consultez Régions et points de terminaison.

  • Dans cette rubrique, les identifiants d'accès sont récupérés à partir des variables d'environnement. Pour plus d'informations, consultez Configuration des identifiants d'accès.

  • Cette rubrique illustre la création d'une instance OSSClient avec un point de terminaison OSS. Pour d'autres configurations, telles que l'utilisation d'un domaine personnalisé ou l'authentification via des identifiants du Security Token Service (STS), consultez Configuration du client.

  • Le téléchargement multipart utilise les opérations InitiateMultipartUpload, UploadPart et CompleteMultipartUpload. Vous devez disposer de l'autorisation oss:PutObject. Accorder des politiques d'accès personnalisées à un utilisateur RAM.

Processus de téléchargement multipart

Le téléchargement multipart s'effectue en trois étapes :

  1. Initialisez un téléchargement multipart.

    Appelez ossClient.initiateMultipartUpload. OSS renvoie un ID de téléchargement unique au niveau mondial.

  2. Téléchargez les parties.

    Appelez ossClient.uploadPart pour télécharger les données de la partie.

    Remarque
    • Le numéro de partie identifie la position d'une partie au sein de l'objet. Le téléchargement de données avec le même numéro de partie écrase la partie existante.

    • OSS renvoie le hachage MD5 des données de la partie reçues dans l'en-tête ETag de la réponse.

    • OSS calcule le hachage MD5 des données téléchargées et le compare au hachage calculé par le SDK. En cas de non-concordance, le code d'erreur InvalidDigest est renvoyé.

  3. Finalisez le téléchargement multipart.

    Une fois toutes les parties téléchargées, appelez ossClient.completeMultipartUpload pour fusionner les parties en un objet complet.

Exemple de code

L'exemple suivant présente le processus complet de téléchargement multipart :

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.internal.Mimetypes;
import com.aliyun.oss.model.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class Demo {

    public static void main(String[] args) throws Exception {
        // Use the endpoint of the China (Hangzhou) region as an example. Specify the actual endpoint.
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the bucket name, for example, examplebucket.
        String bucketName = "examplebucket";
        // Specify the full path of the object, for example, exampledir/exampleobject.txt. The full path cannot contain the bucket name.
        String objectName = "exampledir/exampleobject.txt";
        // The path of the local file to upload.
        String filePath = "D:\\localpath\\examplefile.txt";
        // Specify the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou.
        String region = "cn-hangzhou";

        // Create an OSSClient instance.
        // When the OSSClient instance is no longer used, call the shutdown method to release resources.
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(credentialsProvider)
                .clientConfiguration(clientBuilderConfiguration)
                .region(region)
                .build();

        try {
            // Create an InitiateMultipartUploadRequest object.
            InitiateMultipartUploadRequest request = new InitiateMultipartUploadRequest(bucketName, objectName);

            // Create an ObjectMetadata object and set the Content-Type.
            ObjectMetadata metadata = new ObjectMetadata();
            if (metadata.getContentType() == null) {
                metadata.setContentType(Mimetypes.getInstance().getMimetype(new File(filePath), objectName));
            }
            System.out.println("Content-Type: " + metadata.getContentType());

            // Bind the metadata to the upload request.
            request.setObjectMetadata(metadata);

            // Initialize the multipart upload.
            InitiateMultipartUploadResult upresult = ossClient.initiateMultipartUpload(request);
            // Return the upload ID.
            String uploadId = upresult.getUploadId();

            // partETags is a collection of PartETag objects. A PartETag object consists of the ETag and part number of a part.
            List<PartETag> partETags = new ArrayList<PartETag>();
            // The size of each part. This is used to calculate the number of parts. Unit: bytes.
            // The minimum part size is 100 KB, and the maximum part size is 5 GB. The size of the last part can be smaller than 100 KB.
            // Set the part size to 1 MB.
            final long partSize = 1 * 1024 * 1024L;   

            // Calculate the number of parts based on the size of the data to upload. The following code provides an example of how to obtain the size of the data to upload from a local file using File.length().
            final File sampleFile = new File(filePath);
            long fileLength = sampleFile.length();
            int partCount = (int) (fileLength / partSize);
            if (fileLength % partSize != 0) {
                partCount++;
            }
            // Traverse the parts and upload them.
            for (int i = 0; i < partCount; i++) {
                long startPos = i * partSize;
                long curPartSize = (i + 1 == partCount) ? (fileLength - startPos) : partSize;
                UploadPartRequest uploadPartRequest = new UploadPartRequest();
                uploadPartRequest.setBucketName(bucketName);
                uploadPartRequest.setKey(objectName);
                uploadPartRequest.setUploadId(uploadId);
                // Set the stream of the part to upload.
                // The following code provides an example of how to create a FileInputStream object from a local file and skip the specified data using the InputStream.skip() method.
                InputStream instream = new FileInputStream(sampleFile);
                instream.skip(startPos);
                uploadPartRequest.setInputStream(instream);
                // Set the part size.
                uploadPartRequest.setPartSize(curPartSize);
                // Set the part number. Each uploaded part has a part number that ranges from 1 to 10,000. If the part number is not in the range, OSS returns the InvalidArgument error code.
                uploadPartRequest.setPartNumber(i + 1);
                // Parts do not need to be uploaded in sequence. They can even be uploaded from different clients. OSS sorts the parts by part number to create a complete object.
                UploadPartResult uploadPartResult = ossClient.uploadPart(uploadPartRequest);
                // After each part is uploaded, the OSS response includes a PartETag. The PartETag is saved in partETags.
                partETags.add(uploadPartResult.getPartETag());

                // Close the stream.
                instream.close();
            }

            // Create a CompleteMultipartUploadRequest object.
            // When you complete the multipart upload, you must provide all valid partETags. After OSS receives the submitted partETags, it verifies the validity of each part. After all parts are verified, OSS combines these parts into a complete object.
            CompleteMultipartUploadRequest completeMultipartUploadRequest =
                    new CompleteMultipartUploadRequest(bucketName, objectName, uploadId, partETags);

            // Complete the multipart upload.
            CompleteMultipartUploadResult completeMultipartUploadResult = ossClient.completeMultipartUpload(completeMultipartUploadRequest);
            System.out.println("Upload successful, ETag: " + completeMultipartUploadResult.getETag());

        } 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 a 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();
            }
        }
    }
}

Scénarios courants

Définir les métadonnées lors de l'initialisation d'un téléchargement multipart

Définissez les métadonnées lors de l'initialisation du téléchargement multipart :

// Create an InitiateMultipartUploadRequest object.
InitiateMultipartUploadRequest request = new InitiateMultipartUploadRequest(bucketName, objectName);

ObjectMetadata metadata = new ObjectMetadata();
metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
// Specify the web page caching behavior of the object.
metadata.setCacheControl("no-cache");
// Specify the name of the object when it is downloaded.
metadata.setContentDisposition("attachment;filename=oss_MultipartUpload.txt");
// Specify the content encoding format of the object.
metadata.setContentEncoding(OSSConstants.DEFAULT_CHARSET_NAME);
// Specify whether to overwrite an object that has the same name when you initialize the multipart upload. In this example, this parameter is set to true, which indicates that the object that has the same name is not overwritten.
metadata.setHeader("x-oss-forbid-overwrite", "true");
// Specify the server-side encryption method used to upload each part of the object.
metadata.setHeader(OSSHeaders.OSS_SERVER_SIDE_ENCRYPTION, ObjectMetadata.KMS_SERVER_SIDE_ENCRYPTION);
// Specify the encryption algorithm of the object. If this option is not specified, the AES256 encryption algorithm is used.
metadata.setHeader(OSSHeaders.OSS_SERVER_SIDE_DATA_ENCRYPTION, ObjectMetadata.KMS_SERVER_SIDE_ENCRYPTION);
// Specify the customer master key (CMK) managed by KMS.
metadata.setHeader(OSSHeaders.OSS_SERVER_SIDE_ENCRYPTION_KEY_ID, "9468da86-3509-4f8d-a61e-6eab1eac****");
// Specify the storage class of the object.
metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard);
// Specify the object tags. You can specify multiple tags at the same time.
metadata.setHeader(OSSHeaders.OSS_TAGGING, "a:1");
request.setObjectMetadata(metadata);

// Automatically set the Content-Type based on the file. If this parameter is not set, the default Content-Type is application/octet-stream.
if (metadata.getContentType() == null) {
    metadata.setContentType(Mimetypes.getInstance().getMimetype(new File(filePath), objectName));
}

// Bind the metadata to the upload request.
request.setObjectMetadata(metadata);
// Initialize the multipart upload.
InitiateMultipartUploadResult upresult = ossClient.initiateMultipartUpload(request);

Définir les autorisations d'accès aux objets lors de la finalisation d'un téléchargement multipart

Définissez les autorisations d'accès aux objets lors de la finalisation d'un téléchargement multipart :

completeMultipartUploadRequest.setObjectACL(CannedAccessControlList.Private);

Traiter automatiquement les ETag des parties lors de la finalisation d'un téléchargement multipart

Traitez automatiquement les ETag des parties lors de la finalisation d'un téléchargement multipart :

// Specify whether to list all parts that have been uploaded for the current upload ID. You can set partETags in CompleteMultipartUploadRequest to null to merge parts into a complete object by listing the parts on the server only if you use Java SDK 3.14.0 or later.
Map<String, String> headers = new HashMap<String, String>();
// If you specify x-oss-complete-all:yes, OSS lists all parts that have been uploaded for the current upload ID, sorts the parts by part number, and then runs the CompleteMultipartUpload operation.
// If you specify x-oss-complete-all:yes, you cannot specify the body. Otherwise, an error is reported.
headers.put("x-oss-complete-all","yes");
completeMultipartUploadRequest.setHeaders(headers);

Annuler un téléchargement multipart

Appelez abortMultipartUpload avec l'ID de téléchargement obtenu lors de l'appel à InitiateMultipartUpload pour annuler un téléchargement multipart. Après l'annulation, l'ID de téléchargement devient invalide et toutes les parties téléchargées sont supprimées.

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        // Use the endpoint of the China (Hangzhou) region as an example. Specify the actual endpoint.
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the bucket name, for example, examplebucket.
        String bucketName = "examplebucket";
        // Specify the full path of the object, for example, exampledir/exampleobject.txt. The full path cannot contain the bucket name.
        String objectName = "exampledir/exampleobject.txt";
        // Specify the upload ID, for example, 0004B999EF518A1FE585B0C9360D****. The upload ID is returned after the InitiateMultipartUpload operation is called to initialize the multipart upload.
        String uploadId = "0004B999EF518A1FE585B0C9360D****";
        // Specify the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou.
        String region = "cn-hangzhou";

        // Create an OSSClient instance.
        // When the OSSClient instance is no longer used, call the shutdown method to release resources.
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();
        
        try {
            // Cancel the multipart upload.
            AbortMultipartUploadRequest abortMultipartUploadRequest =
                    new AbortMultipartUploadRequest(bucketName, objectName, uploadId);
            ossClient.abortMultipartUpload(abortMultipartUploadRequest);
        } 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();
            }
        }
    }
}

Lister les parties téléchargées

Appelez listParts avec l'ID de téléchargement obtenu lors de l'appel à InitiateMultipartUpload pour lister toutes les parties téléchargées.

Lister les parties téléchargées

Listez les parties téléchargées :

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        // Use the endpoint of the China (Hangzhou) region as an example. Specify the actual endpoint.
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the bucket name, for example, examplebucket.
        String bucketName = "examplebucket";
        // Specify the full path of the object, for example, exampledir/exampleobject.txt. The full path cannot contain the bucket name.
        String objectName = "exampledir/exampleobject.txt";
        // Specify the upload ID, for example, 0004B999EF518A1FE585B0C9360D****. The upload ID is returned after the InitiateMultipartUpload operation is called to initialize the multipart upload and before the CompleteMultipartUpload operation is called to complete the multipart upload.
        String uploadId = "0004B999EF518A1FE585B0C9360D****";
        // Specify the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou.
        String region = "cn-hangzhou";

        // Create an OSSClient instance.
        // When the OSSClient instance is no longer used, call the shutdown method to release resources.
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();
        
        try {
            // List the uploaded parts.
            ListPartsRequest listPartsRequest = new ListPartsRequest(bucketName, objectName, uploadId);
            // Set the upload ID.
            //listPartsRequest.setUploadId(uploadId);
            // Set the number of parts on each page to 100 for paging. By default, 1,000 parts are listed.
            listPartsRequest.setMaxParts(100);
            // Specify the start position for the list operation. Only parts whose part numbers are greater than this parameter value are listed.
            listPartsRequest.setPartNumberMarker(2);
            PartListing partListing = ossClient.listParts(listPartsRequest);

            for (PartSummary part : partListing.getParts()) {
                // Obtain the part number.
                System.out.println(part.getPartNumber());
                // Obtain the part data size.
                System.out.println(part.getSize());
                // Obtain the ETag of the part.
                System.out.println(part.getETag());
                // Obtain the last modified time of the part.
                System.out.println(part.getLastModified());
            }
        } 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();
            }
        }
    }
}

Lister toutes les parties téléchargées

La méthode listParts renvoie jusqu'à 1 000 parties par appel. Pour lister toutes les parties lorsque leur nombre dépasse 1 000 :

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        // Use the endpoint of the China (Hangzhou) region as an example. Specify the actual endpoint.
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the bucket name, for example, examplebucket.
        String bucketName = "examplebucket";
        // Specify the full path of the object, for example, exampledir/exampleobject.txt. The full path cannot contain the bucket name.
        String objectName = "exampledir/exampleobject.txt";
        // Specify the upload ID, for example, 0004B999EF518A1FE585B0C9360D****. The upload ID is returned after the InitiateMultipartUpload operation is called to initialize the multipart upload and before the CompleteMultipartUpload operation is called to complete the multipart upload.
        String uploadId = "0004B999EF518A1FE585B0C9360D****";
        // Specify the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou.
        String region = "cn-hangzhou";

        // Create an OSSClient instance.
        // When the OSSClient instance is no longer used, call the shutdown method to release resources.
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();
        
        try {
            // List all uploaded parts.
            PartListing partListing;
            ListPartsRequest listPartsRequest = new ListPartsRequest(bucketName, objectName, uploadId);

            do {
                partListing = ossClient.listParts(listPartsRequest);

                for (PartSummary part : partListing.getParts()) {
                    // Obtain the part number.
                    System.out.println(part.getPartNumber());
                    // Obtain the part data size.
                    System.out.println(part.getSize());
                    // Obtain the ETag of the part.
                    System.out.println(part.getETag());
                    // Obtain the last modified time of the part.
                    System.out.println(part.getLastModified());
                }
                // Specify the start position for the list operation. Only parts whose part numbers are greater than this parameter value are listed.
                listPartsRequest.setPartNumberMarker(partListing.getNextPartNumberMarker());
            } while (partListing.isTruncated());
        } 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();
            }
        }
    }
}

Lister toutes les parties téléchargées par page

Listez toutes les parties avec pagination :

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        // Use the endpoint of the China (Hangzhou) region as an example. Specify the actual endpoint.
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the bucket name, for example, examplebucket.
        String bucketName = "examplebucket";
        // Specify the full path of the object, for example, exampledir/exampleobject.txt. The full path cannot contain the bucket name.
        String objectName = "exampledir/exampleobject.txt";
        // Specify the upload ID, for example, 0004B999EF518A1FE585B0C9360D****. The upload ID is returned after the InitiateMultipartUpload operation is called to initialize the multipart upload and before the CompleteMultipartUpload operation is called to complete the multipart upload.
        String uploadId = "0004B999EF518A1FE585B0C9360D****";
        // Specify the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou.
        String region = "cn-hangzhou";

        // Create an OSSClient instance.
        // When the OSSClient instance is no longer used, call the shutdown method to release resources.
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();
        
        try {
            // List the uploaded parts by page.
            PartListing partListing;
            ListPartsRequest listPartsRequest = new ListPartsRequest(bucketName, objectName, uploadId);
            // Set the number of parts to list on each page to 100 for paginated listing.
            listPartsRequest.setMaxParts(100);

            do {
                partListing = ossClient.listParts(listPartsRequest);

                for (PartSummary part : partListing.getParts()) {
                    // Obtain the part number.
                    System.out.println(part.getPartNumber());
                    // Obtain the part data size.
                    System.out.println(part.getSize());
                    // Obtain the ETag of the part.
                    System.out.println(part.getETag());
                    // Obtain the last modified time of the part.
                    System.out.println(part.getLastModified());
                }

                listPartsRequest.setPartNumberMarker(partListing.getNextPartNumberMarker());

            } while (partListing.isTruncated());
        } 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();
            }
        }
    }
}                    

Lister les événements de téléchargement multipart

Appelez listMultipartUploads pour lister les événements de téléchargement multipart en cours (initialisés mais pas encore finalisés ou annulés). Le tableau suivant décrit les paramètres configurables.

Paramètre

Fonction

Méthodes de configuration

prefix

Renvoie uniquement les objets dont les noms commencent par le préfixe spécifié. Les noms d'objets renvoyés contiennent toujours le préfixe.

ListMultipartUploadsRequest.setPrefix(String prefix)

delimiter

Regroupe les noms d'objets. Les noms d'objets contenant le préfixe spécifié qui apparaissent entre les caractères délimiteurs sont regroupés en un seul élément.

ListMultipartUploadsRequest.setDelimiter(String delimiter)

maxUploads

Nombre maximal d'événements de téléchargement multipart à renvoyer. Valeur par défaut et maximale : 1 000.

ListMultipartUploadsRequest.setMaxUploads(Integer maxUploads)

keyMarker

Liste les événements de téléchargement multipart pour les objets dont les noms sont postérieurs à keyMarker dans l'ordre lexicographique. Utilisé conjointement avec uploadIdMarker pour définir la position de départ.

ListMultipartUploadsRequest.setKeyMarker(String keyMarker)

uploadIdMarker

Utilisé conjointement avec keyMarker pour définir la position de départ. Invalide si keyMarker n'est pas défini. Lorsque keyMarker est défini, les résultats incluent :

  • Les objets dont les noms sont postérieurs à keyMarker dans l'ordre lexicographique.

  • Les événements de téléchargement multipart pour les objets correspondant à keyMarker avec des ID de téléchargement postérieurs à uploadIdMarker.

ListMultipartUploadsRequest.setUploadIdMarker(String uploadIdMarker)

Lister les événements de téléchargement multipart

Listez les événements de téléchargement multipart :

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        // Use the endpoint of the China (Hangzhou) region as an example. Specify the actual endpoint.
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the bucket name, for example, examplebucket.
        String bucketName = "examplebucket";
        // Specify the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou.
        String region = "cn-hangzhou";

        // Create an OSSClient instance.
        // When the OSSClient instance is no longer used, call the shutdown method to release resources.
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();
        
        try {
            // List multipart upload events. By default, 1,000 parts are listed.
            ListMultipartUploadsRequest listMultipartUploadsRequest = new ListMultipartUploadsRequest(bucketName);
            MultipartUploadListing multipartUploadListing = ossClient.listMultipartUploads(listMultipartUploadsRequest);

            for (MultipartUpload multipartUpload : multipartUploadListing.getMultipartUploads()) {
                // Obtain the upload ID.
                System.out.println(multipartUpload.getUploadId());
                // Obtain the key.
                System.out.println(multipartUpload.getKey());
                // Obtain the initialization time of the multipart upload.
                System.out.println(multipartUpload.getInitiated());
            }
        } 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();
            }
        }
    }
}

Lorsque isTruncated est vrai, nextKeyMarker et nextUploadIdMarker indiquent le point de départ pour la prochaine requête de liste, permettant ainsi une récupération paginée.

Lister tous les événements de téléchargement multipart

La méthode listMultipartUploads renvoie jusqu'à 1 000 événements par appel. Pour lister tous les événements lorsque leur nombre dépasse 1 000 :

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        // Use the endpoint of the China (Hangzhou) region as an example. Specify the actual endpoint.
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the bucket name, for example, examplebucket.
        String bucketName = "examplebucket";
        // Specify the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou.
        String region = "cn-hangzhou";

        // Create an OSSClient instance.
        // When the OSSClient instance is no longer used, call the shutdown method to release resources.
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();
        
        try {
            // List multipart upload events.
            MultipartUploadListing multipartUploadListing;
            ListMultipartUploadsRequest listMultipartUploadsRequest = new ListMultipartUploadsRequest(bucketName);

            do {
                multipartUploadListing = ossClient.listMultipartUploads(listMultipartUploadsRequest);

                for (MultipartUpload multipartUpload : multipartUploadListing.getMultipartUploads()) {
                    // Obtain the upload ID.
                    System.out.println(multipartUpload.getUploadId());
                    // Obtain the key.
                    System.out.println(multipartUpload.getKey());
                    // Obtain the initialization time of the multipart upload.
                    System.out.println(multipartUpload.getInitiated());
                }

                listMultipartUploadsRequest.setKeyMarker(multipartUploadListing.getNextKeyMarker());

                listMultipartUploadsRequest.setUploadIdMarker(multipartUploadListing.getNextUploadIdMarker());
            } while (multipartUploadListing.isTruncated());
        } 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();
            }
        }
    }
}

Lister tous les événements de téléchargement par page

Listez tous les événements de téléchargement avec pagination :

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        // Use the endpoint of the China (Hangzhou) region as an example. Specify the actual endpoint.
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the bucket name, for example, examplebucket.
        String bucketName = "examplebucket";
        // Specify the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou.
        String region = "cn-hangzhou";

        // Create an OSSClient instance.
        // When the OSSClient instance is no longer used, call the shutdown method to release resources.
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();
        
        try {
            // List multipart upload events.
            MultipartUploadListing multipartUploadListing;
            ListMultipartUploadsRequest listMultipartUploadsRequest = new ListMultipartUploadsRequest(bucketName);
            // Set the number of multipart upload events to list on each page.
            listMultipartUploadsRequest.setMaxUploads(50);

            do {
                multipartUploadListing = ossClient.listMultipartUploads(listMultipartUploadsRequest);

                for (MultipartUpload multipartUpload : multipartUploadListing.getMultipartUploads()) {
                    // Obtain the upload ID.
                    System.out.println(multipartUpload.getUploadId());
                    // Obtain the key.
                    System.out.println(multipartUpload.getKey());
                    // Obtain the initialization time of the multipart upload.
                    System.out.println(multipartUpload.getInitiated());
                }

                listMultipartUploadsRequest.setKeyMarker(multipartUploadListing.getNextKeyMarker());
                listMultipartUploadsRequest.setUploadIdMarker(multipartUploadListing.getNextUploadIdMarker());

            } while (multipartUploadListing.isTruncated());
        } 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();
            }
        }
    }
}

Effectuer un téléchargement multipart pour des flux réseau ou des flux de données

Les exemples de cette rubrique utilisent des fichiers locaux. Pour télécharger des flux réseau ou des flux de données, consultez Téléchargement multipart d'un flux de données.

Références