All Products
Search
Document Center

Object Storage Service:Append upload

Last Updated:Aug 25, 2023

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 by using other Alibaba Cloud services in the same region as OSS, use an internal endpoint. For more information about the regions and endpoints supported by OSS, see Regions and endpoints.

  • 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 Common examples of RAM policies.

  • If the object to which you want to append content does not exist, an appendable object is created when you call the AppendObject operation.

  • 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.

  • The CopyObject operation cannot be performed on appendable objects.

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";

        // Create an OSSClient instance. 
        OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);

        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 object when the object is downloaded. 
            //meta.setContentDisposition("attachment;filename=oss_download.txt");
            // Specify the encoding format for the content 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 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 requests 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 single parameter by using AppendObjectRequest. 
            // Specify the name of the bucket. 
            //appendObjectRequest.setBucketName(bucketName);
            // Specify the name of the object. 
            //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 object metadata. You can specify the metadata of an object 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());

            // Start the second append. 
            // 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 for append upload, see AppendObject.