Manage objects

Last Updated: Oct 23, 2017

In OSS, you can manage the objects in the bucket using a series of interfaces, such as SetObjectAcl, GetObjectAcl, ListObjects, DeleteObject, CopyObject, and DoesObjectExist. The object name is also called the key or the object key.

Check whether an object exists

You can use OSSClient.doesObjectExist to determine whether an object exists.

  1. // Take the Hangzhou endpoint for example. Other regions can be added based on actual conditions
  2. String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
  3. // Cloud account AccessKey has an access to all APIs, it is suggested to create an RAM sub account and use it following Alibaba Cloud Best Security Practices for API access and daily O&M, log on to https://ram.console.aliyun.com to create an account
  4. String accessKeyId = "<yourAccessKeyId>";
  5. String accessKeySecret = "<yourAccessKeySecret>";
  6. // Create an OSSClient instance
  7. OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
  8. // Check whether the object exists
  9. boolean found = ossClient.doesObjectExist("<bucketName>", "<key>")
  10. // Disable the client
  11. ossClient.shutdown();

Object ACL

The object has four access ACLs: default (default value), Private (private-read-write), PublicRead (public-read and private-write), and PublicReadWrite (public-read-write). The detailed description is as follows:

ACL Description
Default The object inherits the read-write permissions of the bucket. The object adopts the default ACL by default.
Private The object is a private resource. Only the owner of the object has permission to read and write the object. Other users have no permission to operate on the object.
PublicRead The object can be read by the public. Only the owner of the object has the permission to read and write the object. Other users only have the permission to read the object.
PublicReadWrite The object can be read and written by the public. That is, all users have the permission to read and write the object.

The object ACL takes precedence over the bucket ACL. For example, if the bucket ACL is private and the object ACL is public-read-write, the system first checks the ACL of the object when a user accesses the object. As a result, all users can access this object even if the bucket is private. If the ACL of an object has never been set, the ACL of this object is the same as that of the bucket where the object is located.

Set the object ACL

You can use OSSClient.setObjectAcl to set the object ACL.

ACL Java SDK values
Private-read-write CannedAccessControlList.Private
Public-read and private-write CannedAccessControlList.PublicRead
Public-read-write CannedAccessControlList.PublicReadWrite

The following code configures the ACL of an object:

  1. // Take the Hangzhou endpoint for example. Other regions can be added based on actual conditions
  2. String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
  3. // Cloud account AccessKey has an access to all APIs, it is suggested to create an RAM sub account and use it following Alibaba Cloud Best Security Practices for API access and daily O&M, log on to https://ram.console.aliyun.com to create an account
  4. String accessKeyId = "<yourAccessKeyId>";
  5. String accessKeySecret = "<yourAccessKeySecret>";
  6. // Create an OSSClient instance
  7. OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
  8. // Set the object ACL
  9. ossClient.setObjectAcl("<bucketName>", "<key>", CannedAccessControlList.PublicRead)
  10. // Disable the client
  11. ossClient.shutdown();

Get the object ACL

You can use OSSClient.getObjectAcl to get the object ACL.

  1. // Take the Hangzhou endpoint for example. Other regions can be added based on actual conditions
  2. String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
  3. // Cloud account AccessKey has an access to all APIs, it is suggested to create an RAM sub account and use it following Alibaba Cloud Best Security Practices for API access and daily O&M, log on to https://ram.console.aliyun.com to create an account
  4. String accessKeyId = "<yourAccessKeyId>";
  5. String accessKeySecret = "<yourAccessKeySecret>";
  6. // Create an OSSClient instance
  7. OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
  8. // Access the object ACL
  9. ObjectAcl objectAcl = ossClient.getObjectAcl("<bucketName>", "<key>");
  10. System.out.println(objectAcl.getPermission().toString());
  11. // Disable the client
  12. ossClient.shutdown();

Get object metadata

Object Meta describes the attributes of objects uploaded to the OSS. These attributes are of two types: HTTP standard attributes (HTTP Headers) and user-defined metainformation (User Meta). Object metadata can be configured when objects are uploaded or copied in various ways. For more information on object metadata, see Object Meta.

You can use OSSClient.getSimplifiedObjectMeta or OSSClient.getObjectMetadata to get the object metadata. The getSimplifiedObjectMeta can only be used to get the object ETag, Size (object size) and LastModified (last modify time). The getObjectMetadata can be used to get all the metadata of the object. The getSimplifiedObjectMeta is more lightweight and faster.

  1. // Take the Hangzhou endpoint for example. Other regions can be added based on actual conditions
  2. String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
  3. // Cloud account AccessKey has an access to all APIs, it is suggested to create an RAM sub account and use it following Alibaba Cloud Best Security Practices for API access and daily O&M, log on to https://ram.console.aliyun.com to create an account
  4. String accessKeyId = "<yourAccessKeyId>";
  5. String accessKeySecret = "<yourAccessKeySecret>";
  6. // Create an OSSClient instance
  7. OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
  8. /// Get part of the metadata of the object
  9. SimplifiedObjectMeta objectMeta = ossClient.getSimplifiedObjectMeta("<bucketName>", "<key>");
  10. System.out.println(objectMeta.getSize());
  11. System.out.println(objectMeta.getETag());
  12. System.out.println(objectMeta.getLastModified());
  13. /// Get all the metadata of the object
  14. ObjectMetadata metadata = ossClient.getObjectMetadata("<bucketName>", "<key>");
  15. System.out.println(metadata.getContentType());
  16. System.out.println(metadata.getLastModified());
  17. System.out.println(metadata.getExpirationTime());
  18. // Disable the client
  19. ossClient.shutdown();

List objects in a bucket

You can use OSSClient.listObjects to list all the objects in the bucket. The listObjects interface has three types of parameter formats:

  • ObjectListing listObjects(String bucketName)
  • ObjectListing listObjects(String bucketName, String prefix)
  • ObjectListing listObjects(ListObjectsRequest listObjectsRequest)

The first two types are called simple list. They can return a maximum of 100 objects. The parameter prefix specifies the prefix of the returned object. The last type provides multiple filtering features to implement flexible queries.

The parameters of the ObjectListing interface are as follows:

Parameter Meaning Method
ObjectSummaries Specifies the returned object meta. List<OSSObjectSummary> getObjectSummaries()
Prefix Starting prefix of the results of the current query. String getPrefix()
Delimiter A character used to group object names. String getDelimiter()
Marker Marks the origin of the current List Object request. String getMarker()
MaxKeys The maximum number of returned results in response to the request. int getMaxKeys()
NextMarker Marks the origin of the next List Object request. String getNextMarker()
IsTruncated Specifies whether all results have been returned. boolean isTruncated()
CommonPrefixes If the delimiter parameter is specified in the request, the response contains the CommonPrefixes element. This element indicates the set of objects that end with a delimiter and have a common prefix. List<String> getCommonPrefixes()
EncodingType Specifies the encoding type for the returned results. String getEncodingType()

Note: Complete listObjects code can be found at GitHub.

Simple list

The following code lists the objects under the bucket. A maximum of 100 objects can be listed.

  1. // Take the Hangzhou endpoint for example. Other regions can be added based on actual conditions
  2. String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
  3. // Cloud account AccessKey has an access to all APIs, it is suggested to create an RAM sub account and use it following Alibaba Cloud Best Security Practices for API access and daily O&M, log on to https://ram.console.aliyun.com to create an account
  4. String accessKeyId = "<yourAccessKeyId>";
  5. String accessKeySecret = "<yourAccessKeySecret>";
  6. // Create an OSSClient instance
  7. OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
  8. // List the objects
  9. ObjectListing objectListing = ossClient.listObjects("<bucketName>", "<KeyPrifex>");
  10. List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
  11. for (OSSObjectSummary s : sums) {
  12. System.out.println("\t" + s.getKey());
  13. }
  14. // Disable the client
  15. ossClient.shutdown();

The following code lists the objects with the specified prefix under the bucket. A maximum of 100 objects can be listed.

  1. ObjectListing objectListing = ossClient.listObjects("<bucketName>", "<KeyPrifex>");
  2. List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
  3. for (OSSObjectSummary s : sums) {
  4. System.out.println("\t" + s.getKey());
  5. }

List objects through ListObjectsRequest

You can set parameters of ListObjectsReques to achieve various flexible queries. Configurable parameters of the ListObjectsReques interface include the following:

Parameter Role Method
Prefix The keys of returned objects must use the prefix. setPrefix(String prefix)
Delimiter A character used to group object names. All the objects whose names contain the specified prefix and appear before the delimiter for the first time form a group of elements called CommonPrefixes. setDelimiter(String delimiter)
Marker Sets the returned results to begin from the first entry after the marker in alphabetical order. setMarker(String marker)
MaxKeys The maximum number of objects returned for one request. If this parameter is not set, the default value of 100 applies. The max-keys value cannot exceed 1,000. setMaxKeys(Integer maxKeys)
EncodingType The encoding method of names of objects in the request response body. The url is supported. setEncodingType(String encodingType)

Specify the maximum number of returned results

  1. // Take the Hangzhou endpoint for example. Other regions can be added based on actual conditions
  2. String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
  3. // Cloud account AccessKey has an access to all APIs, it is suggested to create an RAM sub account and use it following Alibaba Cloud Best Security Practices for API access and daily O&M, log on to https://ram.console.aliyun.com to create an account
  4. String accessKeyId = "<yourAccessKeyId>";
  5. String accessKeySecret = "<yourAccessKeySecret>";
  6. // Create an OSSClient instance
  7. OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
  8. final int maxKeys = 200;
  9. // List the objects
  10. ObjectListing objectListing = ossClient.listObjects(new ListObjectsRequest("<bucketName>").withMaxKeys(maxKeys));
  11. List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
  12. for (OSSObjectSummary s : sums) {
  13. System.out.println("\t" + s.getKey());
  14. }
  15. // Disable the client
  16. ossClient.shutdown();

Return the object with the specified prefix

A maximum of 100 results can be returned.

  1. final String keyPrefix = "<keyPrefix>"
  2. ObjectListing objectListing = ossClient.listObjects(new ListObjectsRequest("<bucketName>").withPrefix(keyPrefix));
  3. List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
  4. for (OSSObjectSummary s : sums) {
  5. System.out.println("\t" + s.getKey());
  6. }

Return the results after the specified object

The specified object is not included. A maximum of 100 objects can be returned.

  1. final String keyMarker = "<keyMarker>"
  2. ObjectListing objectListing = ossClient.listObjects(new ListObjectsRequest("<bucketName>").withMarker(keyMarker));
  3. List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
  4. for (OSSObjectSummary s : sums) {
  5. System.out.println("\t" + s.getKey());
  6. }

Retrieve all objects by page

Retrieves all objects by page. A maximum of maxKeys objects can be returned for each page.

  1. final int maxKeys = 200;
  2. String nextMarker = null;
  3. do {
  4. objectListing = ossClient.listObjects(new ListObjectsRequest("<bucketName>").withMarker(nextMarker).withMaxKeys(maxKeys));
  5. List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
  6. for (OSSObjectSummary s : sums) {
  7. System.out.println("\t" + s.getKey());
  8. }
  9. nextMarker = objectListing.getNextMarker();
  10. } while (objectListing.isTruncated());

Retrieve all the objects after a specified object by page

Retrieves all objects after a specified object by page. A maximum of maxKeys objects can be returned for each page.

  1. final int maxKeys = 200;
  2. String nextMarker = "<nextMarker>";
  3. do {
  4. objectListing = ossClient.listObjects(new ListObjectsRequest("<bucketName>").withMarker(nextMarker).withMaxKeys(maxKeys));
  5. List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
  6. for (OSSObjectSummary s : sums) {
  7. System.out.println("\t" + s.getKey());
  8. }
  9. nextMarker = objectListing.getNextMarker();
  10. } while (objectListing.isTruncated());

Retrieve all objects with the specified prefix by page.

Retrieves all objects with the specified prefix by page. A maximum of maxKeys objects can be returned for each page.

  1. final int maxKeys = 200;
  2. final String keyPrefix = "<keyPrefix>";
  3. String nextMarker = "<nextMarker>";
  4. do {
  5. objectListing = ossClient.listObjects(new ListObjectsRequest("<bucketName>").
  6. withPrefix(keyPrefix).withMarker(nextMarker).withMaxKeys(maxKeys));
  7. List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
  8. for (OSSObjectSummary s : sums) {
  9. System.out.println("\t" + s.getKey());
  10. }
  11. nextMarker = objectListing.getNextMarker();
  12. } while (objectListing.isTruncated());

Specify the object name encoding

If the object contains special characters, such as ', ", &, <, >, or Chinese characters, the object must be encoded for transmission. OSS currently supports url encoding.

  1. final int maxKeys = 200;
  2. final String keyPrefix = "<keyPrefix>";
  3. String nextMarker = "<nextMarker>";
  4. ObjectListing objectListing;
  5. do {
  6. ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName);
  7. listObjectsRequest.setPrefix(keyPrefix);
  8. listObjectsRequest.setMaxKeys(maxKeys);
  9. listObjectsRequest.setMarker(nextMarker);
  10. // Specify the object name encoding for transmission
  11. listObjectsRequest.setEncodingType("url");
  12. objectListing = ossClient.listObjects(listObjectsRequest);
  13. // Object decoding
  14. for (OSSObjectSummary objectSummary: objectListing.getObjectSummaries()) {
  15. System.out.println("Key:" + URLDecoder.decode(objectSummary.getKey(), "UTF-8"));
  16. }
  17. // CommonPrefixe decoding
  18. for (String commonPrefixes: objectListing.getCommonPrefixes()) {
  19. System.out.println("CommonPrefixes:" + URLDecoder.decode(commonPrefixes, "UTF-8"));
  20. }
  21. // NextMarker decoding
  22. if (objectListing.getNextMarker() != null) {
  23. nextMarker = URLDecoder.decode(objectListing.getNextMarker(), "UTF-8");
  24. }
  25. } while (objectListing.isTruncated());

Simulate a folder

The OSS does not use folders. All elements are stored as objects. Creating a simulated folder itself means creating an object with a size of 0. This object can be uploaded and downloaded, but the OSS console displays the object ended with a slash as a folder.

You can use the Delimiter and Prefix parameters together to simulate the folder feature. Combinations of Delimiter and Prefix serve the following purposes:

  • Setting Prefix as the name of a folder enumerates the objects starting with this prefix, recursively returning all objects and subfolders (directories) in this folder. The object name is shown in Contents.

  • When the slash (/) is used as the delimiter, the returned values enumerate only the objects and subfolders (directories) in the folder, and the subfolders (directories) in the folder are returned in CommonPrefixes, then the Recursive objects and folders in the subfolders are not displayed.

Note:

  • For more information on simulated object updates, see Folder Simulation.

  • Complete object creation code can be found at GitHub.

If the bucket contains four objects: oss.jpg, fun/test.jpg, fun/movie/001.avi, and fun/movie/007.avi. The / symbol serves as the separator for folders. The following example demonstrates how to simulate the folder feature.

List all objects in a bucket

The following code retrieves all objects from a bucket:

  1. // Construct the ListObjectsRequest request
  2. ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName);
  3. // List objects
  4. ObjectListing listing = ossClient.listObjects(listObjectsRequest);
  5. // Traverse all objects
  6. System.out.println("Objects:");
  7. for (OSSObjectSummary objectSummary : listing.getObjectSummaries()) {
  8. System.out.println(objectSummary.getKey());
  9. }
  10. // Traverse all CommonPrefix
  11. System.out.println("CommonPrefixs:");
  12. for (String commonPrefix : listing.getCommonPrefixes()) {
  13. System.out.println(commonPrefix);
  14. }

Output:

  1. Objects:
  2. fun/movie/001.avi
  3. fun/movie/007.avi
  4. fun/test.jpg
  5. oss.jpg
  6. CommonPrefixs:

Recursively list all objects in a directory

You can set the Prefix parameter to retrieve all the objects under a directory (fun/):

  1. // Construct the ListObjectsRequest request
  2. ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName);
  3. listObjectsRequest.setPrefix("fun/");
  4. // Recursively list all objects in the fun directory
  5. ObjectListing listing = ossClient.listObjects(listObjectsRequest);
  6. // Traverse all objects
  7. System.out.println("Objects:");
  8. for (OSSObjectSummary objectSummary : listing.getObjectSummaries()) {
  9. System.out.println(objectSummary.getKey());
  10. }
  11. // Traverse all CommonPrefix
  12. System.out.println("\nCommonPrefixs:");
  13. for (String commonPrefix : listing.getCommonPrefixes()) {
  14. System.out.println(commonPrefix);
  15. }

Output:

  1. Objects:
  2. fun/movie/001.avi
  3. fun/movie/007.avi
  4. fun/test.jpg
  5. CommonPrefixs:

List objects and subdirectories in a directory

Using Prefix and Delimiter together, you can list the objects and subdirectories under a directory (fun/):

  1. // Construct the ListObjectsRequest request
  2. ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName);
  3. // "/" is the folder separator
  4. listObjectsRequest.setDelimiter("/");
  5. // List all objects and folders in the fun directory
  6. listObjectsRequest.setPrefix("fun/");
  7. ObjectListing listing = ossClient.listObjects(listObjectsRequest);
  8. // Traverse all objects
  9. System.out.println("Objects:");
  10. for (OSSObjectSummary objectSummary : listing.getObjectSummaries()) {
  11. System.out.println(objectSummary.getKey());
  12. }
  13. // Traverse all CommonPrefix
  14. System.out.println("\nCommonPrefixs:");
  15. for (String commonPrefix : listing.getCommonPrefixes()) {
  16. System.out.println(commonPrefix);
  17. }

Output:

  1. Objects:
  2. fun/test.jpg
  3. CommonPrefixs:
  4. fun/movie/

Note:

  • In the returned results, the ObjectSummaries list contains the objects in the fun directory.

  • The CommonPrefixs list contains all subfolders in the fun directory. The fun/movie/001.avi and fun/movie/007.avi objects are not listed, because they are in the movie directory under the fun folder.

Delete an object

Delete a single object:

You can use OSSClient.deleteObject to delete a single object.

  1. // Take the Hangzhou endpoint for example. Other regions can be added based on actual conditions
  2. String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
  3. // Cloud account AccessKey has an access to all APIs, it is suggested to create an RAM sub account and use it following Alibaba Cloud Best Security Practices for API access and daily O&M, log on to https://ram.console.aliyun.com to create an account
  4. String accessKeyId = "<yourAccessKeyId>";
  5. String accessKeySecret = "<yourAccessKeySecret>";
  6. // Create an OSSClient instance
  7. OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
  8. // Delete the object
  9. ossClient.deleteObject("<bucketName>", "<key>");
  10. // Disable the client
  11. ossClient.shutdown();

Delete multiple objects:

You can use OSSClient.deleteObject to delete multiple objects.

  1. public DeleteObjectsResult deleteObjects(DeleteObjectsRequest deleteObjectsRequest)

A maximum of 1,000 objects can be deleted in one request. Two return modes are available: the Verbose mode and the Quiet mode:

  • Verbose mode: Return the results of successfully deleted objects, that is, DeleteObjectsResult.getDeletedObjects. Default mode.

  • Quiet mode: Return the results of objects with errors during the deletion, that is, DeleteObjectsResult.getDeletedObjects.

Configurable parameters of the DeleteObjectsRequest interface include the following:

Parameter Role Method
Keys Objects to be deleted. setKeys(List<String>)
Quiet Return mode. Verbose is the default mode. If this parameter is set to “true”, Quiet mode applies; if it is set to “false”, Verbose mode applies. setQuiet(boolean)
EncodingType Specifies to encode the returned key. Currently url is supported. setEncodingType(String)

DeleteObjectsResult parameters include the following:

Parameter Meaning Method
deletedObjects The deletion result, showing the successfully deleted objects in Verbose mode and objects failed to be deleted in Quiet mode. List<String> getDeletedObjects()
EncodingType Encodes the key in deletedObjects. If it is null, it indicates no encoding applies. getEncodingType()
  1. // Take the Hangzhou endpoint for example. Other regions can be added based on actual conditions
  2. String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
  3. // Cloud account AccessKey has an access to all APIs, it is suggested to create an RAM sub account and use it following Alibaba Cloud Best Security Practices for API access and daily O&M, log on to https://ram.console.aliyun.com to create an account
  4. String accessKeyId = "<yourAccessKeyId>";
  5. String accessKeySecret = "<yourAccessKeySecret>";
  6. // Create an OSSClient instance
  7. OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
  8. // Delete the object
  9. List<String> keys = new ArrayList<String>();
  10. keys.add("key0");
  11. keys.add("key1");
  12. keys.add("key2");
  13. DeleteObjectsResult deleteObjectsResult = ossClient.deleteObjects(new DeleteObjectsRequest("<bucketName>").withKeys(keys));
  14. List<String> deletedObjects = deleteObjectsResult.getDeletedObjects();
  15. // Disable the client
  16. ossClient.shutdown();

Note: Complete code for multiple object deletion can be found at GitHub.

Copy an object

You can copy an object from one bucket to another in the same region (Hangzhou, Shenzhen, Qingdao, and so on). You can use the OSSClient.copyObject method.

  • CopyObjectResult copyObject(String sourceBucketName, String sourceKey, String destinationBucketName, String destinationKey)
  • CopyObjectResult copyObject(CopyObjectRequest copyObjectRequest)

The first method specifies the source bucket/key and the target bucket/key. The content and metadata of the target object is the same as those of the source object. This is called the simple copy. The second method allows you to specify the reason data of the target object and the constraints of the COPY operation. In the COPY operation, if the source object address and target object address are the same, the meta information of the source object is replaced directly.

Configurable parameters of the CopyObjectRequest interface include the following:

Parameter Role Method
sourceBucketName Name of the bucket of the source object. setSourceBucketName(String sourceBucketName)
sourceKey Key of the source object. setSourceKey(String sourceKey)
destinationBucketName Name of the bucket of the target object. setDestinationBucketName(String destinationBucketName)
destinationKey Key of the target object. setDestinationKey(String destinationKey)
newObjectMetadata Meta information of the target object. setNewObjectMetadata(ObjectMetadata newObjectMetadata)
matchingETagConstraints Constraints of the COPY operation. If the source object ETag value is equal to the provided ETag, the COPY operation is executed. Otherwise, an error is returned. setMatchingETagConstraints(List<String> matchingETagConstraints)
nonmatchingEtagConstraints Constraints of the COPY operation. If the source object ETag value is not equal to the user-provided ETag, the COPY operation is executed. Otherwise, an error is returned. setNonmatchingETagConstraints(List<String> nonmatchingEtagConstraints)
unmodifiedSinceConstraint Constraints of the COPY operation. If the specified time in the input parameter is the same as or later than the actual modification time of the object, the object is copied normally. Otherwise, an error is returned. setUnmodifiedSinceConstraint(Date unmodifiedSinceConstraint)
modifiedSinceConstraint Constraints of the COPY operation. If the source object has been modified after the time specified by the user, the COPY operation is executed. Otherwise, an error is returned. setModifiedSinceConstraint(Date modifiedSinceConstraint)

Parameters of the CopyObjectRequest interface include the following:

Parameter Meaning Method
etag The unique identifier of the OSS objects String getETag()
lastModified Time when the object was last modified Date getLastModified()

Note:

  • You must have permissions to operate the source object. Otherwise the operation may fail.

  • This operation cannot copy data across regions. For example, an object in a bucket in the Hangzhou region cannot be copied to one in Qingdao.

  • This operation supports a maximum object size of 1 GB.

Simple copy

  1. // Take the Hangzhou endpoint for example. Other regions can be added based on actual conditions
  2. String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
  3. // Cloud account AccessKey has an access to all APIs, it is suggested to create an RAM sub account and use it following Alibaba Cloud Best Security Practices for API access and daily O&M, log on to https://ram.console.aliyun.com to create an account
  4. String accessKeyId = "<yourAccessKeyId>";
  5. String accessKeySecret = "<yourAccessKeySecret>";
  6. // Create an OSSClient instance
  7. OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
  8. // Copy the object
  9. CopyObjectResult result = ossClient.copyObject("<srcBucketName>", "<srcKey>", "<destBucketName>", "<destKey>");
  10. System.out.println("ETag: " + result.getETag() + " LastModified: " + result.getLastModified());
  11. // Disable the client
  12. ossClient.shutdown();

Use CopyObjectRequest to copy objects

You can also use CopyObjectRequest to copy objects:

  1. // Take the Hangzhou endpoint for example. Other regions can be added based on actual conditions
  2. String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
  3. // Cloud account AccessKey has an access to all APIs, it is suggested to create an RAM sub account and use it following Alibaba Cloud Best Security Practices for API access and daily O&M, log on to https://ram.console.aliyun.com to create an account
  4. String accessKeyId = "<yourAccessKeyId>";
  5. String accessKeySecret = "<yourAccessKeySecret>";
  6. // Create an OSSClient instance
  7. OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
  8. // Create a CopyObjectRequest object
  9. CopyObjectRequest copyObjectRequest = new CopyObjectRequest(srcBucketName, srcKey, destBucketName, destKey);
  10. // Set the new metadata
  11. ObjectMetadata meta = new ObjectMetadata();
  12. meta.setContentType("text/html");
  13. copyObjectRequest.setNewObjectMetadata(meta);
  14. // Copy the object
  15. CopyObjectResult result = ossClient.copyObject(copyObjectRequest);
  16. System.out.println("ETag: " + result.getETag() + " LastModified: " + result.getLastModified());
  17. // Disable the client
  18. ossClient.shutdown();

Copy a large object

CopyObject only support copying objects smaller than 1 GB in size. For large objects, you must use the multipart copy (Upload Part Copy). For more information on Upload Part Copy, see Upload Part Copy. The Upload Part Copy operation is divided into three steps:

  • Initialize the multipart copy task OSSClient.initiateMultipartUpload.

  • During the multipart copy operation OSSClient.uploadPartCopy, all the other parts except the last one must be larger than 100 KB in size.

  • Submit the multipart copy task OSSClient.completeMultipartUpload.

Note: Complete code for Upload Part Copy can be found at GitHub.

  1. String sourceBucketName = "<sourceBucketName>";
  2. String sourceKey = "<sourceKey>";
  3. String targetBucketName = "<targetBucketName>";
  4. String targetKey = "<targetKey>";
  5. // Obtain the size of the copied object
  6. ObjectMetadata objectMetadata = ossClient.getObjectMetadata(sourceBucketName, sourceKey);
  7. long contentLength = objectMetadata.getContentLength();
  8. // Part size: 10 MB
  9. long partSize = 1024 * 1024 * 10;
  10. // Calculate the number of parts
  11. int partCount = (int) (contentLength / partSize);
  12. if (contentLength % partSize != 0) {
  13. partCount++;
  14. }
  15. System.out.println("total part count:" + partCount);
  16. // Initialize the COPY task
  17. InitiateMultipartUploadRequest initiateMultipartUploadRequest = new InitiateMultipartUploadRequest(targetBucketName, targetKey);
  18. InitiateMultipartUploadResult initiateMultipartUploadResult = ossClient.initiateMultipartUpload(initiateMultipartUploadRequest);
  19. String uploadId = initiateMultipartUploadResult.getUploadId();
  20. // Start to copy parts
  21. List<PartETag> partETags = new ArrayList<PartETag>();
  22. for (int i = 0; i < partCount; i++) {
  23. // Calculate the size of each part
  24. long skipBytes = partSize * i;
  25. long size = partSize < contentLength - skipBytes ? partSize : contentLength - skipBytes;
  26. // Create the UploadPartCopyRequest
  27. UploadPartCopyRequest uploadPartCopyRequest =
  28. new UploadPartCopyRequest(sourceBucketName, sourceKey, targetBucketName, targetKey);
  29. uploadPartCopyRequest.setUploadId(uploadId);
  30. uploadPartCopyRequest.setPartSize(size);
  31. uploadPartCopyRequest.setBeginIndex(skipBytes);
  32. uploadPartCopyRequest.setPartNumber(i + 1);
  33. UploadPartCopyResult uploadPartCopyResult = ossClient.uploadPartCopy(uploadPartCopyRequest);
  34. // Save the returned PartETags to the list
  35. partETags.add(uploadPartCopyResult.getPartETag());
  36. }
  37. // Submit the Upload Part Copy task
  38. CompleteMultipartUploadRequest completeMultipartUploadRequest = new CompleteMultipartUploadRequest(
  39. targetBucketName, targetKey, uploadId, partETags);
  40. ossClient.completeMultipartUpload(completeMultipartUploadRequest);

Note:

  • During the Upload Part Copy operation, you can specify the target object metadata through InitiateMultipartUploadRequest.

  • The Upload Part Copy operation also supports constraints, which can be specified through UploadPartCopyRequest.

Restore archive objects

Archive objects can be read-only when being restored. For detailed description, see Archive Storage. The process of changing the archive object states is as follows:

  • Archive objects are in the frozen state to begin with.

  • Once you submit the restore action, the server executes the operation, and objects enter the restoring state.

  • Objects can be read after they are restored.

  • The restored state lasts for one day by default. You can prolong the state to a maximum of seven days. Once this period ends, objects return to the frozen state.

  1. ObjectMetadata objectMetadata = ossClient.getObjectMetadata(bucketName, key);
  2. // check whether the object is archive class
  3. StorageClass storageClass = objectMetadata.getObjectStorageClass();
  4. if (storageClass == StorageClass.Archive) {
  5. // restore object
  6. ossClient.restoreObject(bucketName, key);
  7. // wait for restore completed
  8. do {
  9. Thread.sleep(1000);
  10. objectMetadata = ossClient.getObjectMetadata(bucketName, key);
  11. } while (!objectMetadata.isRestoreCompleted());
  12. }
  13. // get restored object
  14. OSSObject ossObject = ossClient.getObject(bucketName, key);
  15. ossObject.getObjectContent().close();

Note:

  • Complete code for the preceding example can be found at GitHub.

  • Do not call the restoreObject interface for non-archive objects.

Thank you! We've received your feedback.