Tous les produits
Search
Centre de documentation

Object Storage Service:Chargement par ajout à l'aide du SDK OSS pour Java 1.0

Dernière mise à jour :Aug 18, 2026

Appelez l'opération AppendObject pour ajouter du contenu à des objets existants pouvant faire l'objet d'un ajout.

Remarques sur l'utilisation

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

  • Les informations d'identification d'accès sont obtenues à partir de variables d'environnement. Pour plus d'informations, consultez la section Configuration des informations d'identification d'accès.

  • Cette rubrique explique comment créer une instance OSSClient avec un endpoint OSS. Pour d'autres configurations, telles que l'utilisation d'un domaine personnalisé ou l'authentification via des informations d'identification du Security Token Service (STS), consultez la page Configuration du client.

  • Si l'objet auquel vous souhaitez ajouter du contenu n'existe pas, l'opération AppendObject crée un objet pouvant faire l'objet d'un ajout.

  • Si l'objet auquel vous souhaitez ajouter du contenu existe déjà :

    • Si l'objet peut faire l'objet d'un ajout et que la position de départ spécifiée pour l'opération d'ajout est égale à la taille actuelle de l'objet, les données sont ajoutées à la fin de l'objet.

    • Si l'objet peut faire l'objet d'un ajout mais que la position de départ spécifiée pour l'opération d'ajout n'est pas égale à la taille actuelle de l'objet, l'erreur PositionNotEqualToLength est renvoyée.

    • Si l'objet ne peut pas faire l'objet d'un ajout, l'erreur ObjectNotAppendable est renvoyée.

Autorisations

Par défaut, un compte Alibaba Cloud dispose de toutes les autorisations. Les utilisateurs RAM ou les rôles RAM associés à un compte Alibaba Cloud ne disposent d'aucune autorisation par défaut. Le compte Alibaba Cloud ou l'administrateur du compte doit accorder les autorisations d'opération via des politiques RAM ou une Bucket Policy.

API

Action

Description

AppendObject

oss:PutObject

Appelez cette opération pour télécharger un objet en l'ajoutant à un objet existant.

oss:PutObjectTagging

Lors du téléchargement d'un objet par ajout à un objet existant, cette autorisation est requise si vous spécifiez des tags d'objet via x-oss-tagging.

Exemples

L'exemple de code suivant montre comment effectuer une opération de chargement par ajout :

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.AppendObjectRequest;
import com.aliyun.oss.model.AppendObjectResult;
import com.aliyun.oss.model.ObjectMetadata;
import java.io.ByteArrayInputStream;

public class Demo {

    public static void main(String[] args) throws Exception {
        // In this example, the endpoint of the China (Hangzhou) region is used. Specify your 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 name of the bucket. Example: examplebucket. 
        String bucketName = "examplebucket";
        // Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt. 
        String objectName = "exampledir/exampleobject.txt";
        String content1 = "Hello OSS A \n";
        String content2 = "Hello OSS B \n";
        String content3 = "Hello OSS C \n";
        // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
        String region = "cn-hangzhou";

        // Create an OSSClient instance. 
        // Call the shutdown method to release associated resources when the OSSClient is no longer in use.
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            ObjectMetadata meta = new ObjectMetadata();
            // Specify the type of content that you want to upload. 
            meta.setContentType("text/plain");
            // Specify the caching behavior of the web page for the object. 
            //meta.setCacheControl("no-cache");
            // Specify the name of the downloaded object. 
            //meta.setContentDisposition("attachment;filename=oss_download.txt");
            // Specify the content encoding of the object. 
            //meta.setContentEncoding(OSSConstants.DEFAULT_CHARSET_NAME);
            // Specify the request header that is used to check whether the content of the received message is the same as the content of the sent message. 
            //meta.setContentMD5("ohhnqLBJFiKkPSBO1eNaUA==");
            // Specify the expiration time. 
            //try {
            //    meta.setExpirationTime(DateUtil.parseRfc822Date("Wed, 08 Jul 2022 16:57:01 GMT"));
            //} catch (ParseException e) {
            //    e.printStackTrace();
            //}
            // Specify the server-side encryption method. In this example, the method is set to SSE-OSS. 
            //meta.setServerSideEncryption(ObjectMetadata.AES_256_SERVER_SIDE_ENCRYPTION);
            // Specify the access control list (ACL) of the object. In this example, the ACL of the object is set to private. 
            //meta.setObjectAcl(CannedAccessControlList.Private);
            // Specify the storage class of the object. 
            //meta.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard);
            // You can add parameters whose names are prefixed with x-oss-meta-* when you call the AppendObject operation to create an appendable object. These parameters cannot be included in the request when you append content to an existing appendable object. Parameters whose names are prefixed with x-oss-meta-* are considered as the metadata of the object. 
            //meta.setHeader("x-oss-meta-author", "Alice");

            // Configure multiple parameters by using AppendObjectRequest. 
            AppendObjectRequest appendObjectRequest = new AppendObjectRequest(bucketName, objectName, new ByteArrayInputStream(content1.getBytes()),meta);

            // Configure a parameter by using AppendObjectRequest. 
            // Specify the name of the bucket. 
            //appendObjectRequest.setBucketName(bucketName);
            // Specify the object name. 
            //appendObjectRequest.setKey(objectName);
            // Specify the content that you want to append. Two types of content are supported: InputStream and File. In this example, the content is set to InputStream. 
            //appendObjectRequest.setInputStream(new ByteArrayInputStream(content1.getBytes()));
            // Specify the content that you want to append. Two types of content are supported: InputStream and File. In this example, the content is set to File. 
            //appendObjectRequest.setFile(new File("D:\\localpath\\examplefile.txt"));
            // Specify the metadata of the object. You can specify the metadata only when you perform the first append operation on the object. 
            //appendObjectRequest.setMetadata(meta);

            // Perform the first append operation. 
            // Specify the position from which the append operation starts. 
            appendObjectRequest.setPosition(0L);
            AppendObjectResult appendObjectResult = ossClient.appendObject(appendObjectRequest);
            // Calculate the CRC-64 value of the object.
            System.out.println(appendObjectResult.getObjectCRC());

            // Perform the second append operation. 
            // NextPosition specifies the position from which the next append operation starts, which is the length of the object. 
            appendObjectRequest.setPosition(appendObjectResult.getNextPosition());
            appendObjectRequest.setInputStream(new ByteArrayInputStream(content2.getBytes()));
            appendObjectResult = ossClient.appendObject(appendObjectRequest);

            // Perform the third append operation. 
            appendObjectRequest.setPosition(appendObjectResult.getNextPosition());
            appendObjectRequest.setInputStream(new ByteArrayInputStream(content3.getBytes()));
            appendObjectResult = ossClient.appendObject(appendObjectRequest);
        } 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();
            }
        }
    }
}

Références

  • Pour consulter l'exemple de code complet relatif au chargement par ajout, rendez-vous sur GitHub.

  • Pour plus d'informations sur l'opération API permettant d'effectuer un chargement par ajout, consultez la page AppendObject.