All Products
Search
Document Center

Object Storage Service:Append upload by using OSS SDK for Java

Last Updated:Oct 22, 2024

You can call the AppendObject operation to append content to existing appendable objects.

Usage notes

  • In this topic, the public endpoint of the China (Hangzhou) region is used. If you want to access OSS from other Alibaba Cloud services in the same region as OSS, use an internal endpoint. For more information about OSS regions and endpoints, see Regions, endpoints and open ports.

  • In this topic, access credentials are obtained from environment variables. For more information about how to configure access credentials, see Configure access credentials.

  • In this topic, an OSSClient instance is created by using an OSS endpoint. If you want to create an OSSClient instance by using custom domain names or Security Token Service (STS), see Create an OSSClient instance.

  • To use append upload, you must have the oss:PutObject permission. For more information, see Attach a custom policy to a RAM user.

  • If the object to which you want to append content does not exist, the AppendObject operation creates an appendable object.

  • If the object to which you want to append content exists:

    • If the object is an appendable object and the specified position from which the append operation starts is equal to the current object size, the data is appended to the end of the object.

    • If the object is an appendable object and the specified position from which the append operation starts is not equal to the current object size, the PositionNotEqualToLength error is returned.

    • If the object is not an appendable object, the ObjectNotAppendable error is returned.

Examples

The following sample code provides an example on how to perform an append upload operation:

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
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. 
        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. The value is calculated based on the ECMA-182 standard. 
            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();
            }
        }
    }
}

References

  • For the complete sample code for append upload, visit GitHub.

  • For more information about the API operation that you can call to perform append upload, see AppendObject.