When versioning is enabled for a bucket, Object Storage Service (OSS) generates a unique ID for each version of all objects in the bucket. The content and access control list (ACL) of existing objects in the bucket remain unchanged. Versioning prevents your data from being accidentally overwritten or deleted and allows you to query or restore previous versions of objects.
Usage notes
Take note of the following items when you upload, list, download, delete, and restore objects in versioning-enabled buckets:
- When versioning is enabled for a bucket, a current version and its previous versions are stored for each object in the bucket.
- The version ID of an object that is uploaded before versioning is enabled is set to null.
- For ease of viewing, all version IDs in the following figures are in the simple format.
For more information about versioning, see Overview.
Upload objects
When you upload an object to a versioning-enabled bucket, OSS generates a unique version ID for the object.

When you call the PutObject operation to upload an object that has the same key as the existing object example.jpg, OSS generates a new version with a unique version ID 222222 for the object and stores the new version as the current version of the object. Version 111111 is stored as a previous version. When you call the PutObject operation to upload an object that has the same key again, OSS generates a new version with a unique version ID 333333 for the object and stores the new version as the current version of the object. Versions 111111 and 222222 are stored as previous versions, as shown in the following figure.

Use the OSS console
- Log on to the OSS console.
- In the left-side navigation pane, click Buckets. On the Buckets page, click the name of the desired bucket.
- In the left-side navigation tree, choose .
- On the Objects page, click Upload.
- Configure the basic settings. The following table describes the parameters.
Parameter Description Upload To Specify the directory in which an object is stored after the object is uploaded to the bucket. - Current: The object is uploaded to the current directory.
- Specified: The object is uploaded to a specific directory. You must enter the name of the directory. If you enter a directory name that does not exist in the bucket, OSS automatically creates the directory and uploads the object to the directory. The directory name must meet the following conventions:
- The name must be 1 to 254 characters in length. The name can contain only UTF-8 characters.
- The name cannot start with a forward slash (/) or a backslash (\).
- The name cannot contain consecutive forward slashes (/).
- The name cannot contain two consecutive periods (
..
).
File ACL Specify the ACL of the object. - Inherited from Bucket: The ACL of the object is the same as that of the bucket.
- Private: Only the object owner and authorized users can read and write the object. Other users cannot access the object.
- Public Read: Only the object owner or authorized users can read and write the object. Other users, including anonymous users, can only read the object. If you set the File ACL parameter to this value, the object can be read by all users. This may result in data leaks and unexpectedly high fees. Proceed with caution.
- Public Read/Write: All users, including anonymous users, can read and write the object. This may result in data leaks and unexpectedly high fees. If a user writes prohibited data or information to the object, your legitimate interests and rights may be infringed. We recommend that you do not set this parameter to Public Read/Write unless necessary.
For more information, see Object ACL.
Upload Acceleration After transfer acceleration is enabled for the bucket to which you want to upload the objects, you can turn on Upload Acceleration if you want to accelerate the upload of the object. For more information, see Enable transfer acceleration.
Files to Upload The files or directories that you want to upload. You can click Select Files to select a local file or click Select Folders to select a directory. You can also drag the local file or directory that you want to upload to the Files to Upload section.
If the selected directory contains an object that you do not want to upload, find the object in the file list in the Files to Upload section and click Remove in the Actions column to remove the object.
Important- When you upload an object that has the same name as an existing object in OSS to a versioning-enabled bucket, the existing object becomes a previous version, and the uploaded object becomes the current version.
- When you upload an object that has the same name as an existing object in OSS to an unversioned bucket, the object that you upload overwrites the existing object.
- Optional:Configure the advanced settings, such as the Storage Class and Encryption Method parameters. The following table describes the parameters.
Parameter Description Storage Class Specify the storage class of the object. - Inherited from Bucket: The storage class of the object is the same as that of the bucket.
- Standard: Standard is suitable for objects that are frequently accessed.
- IA: Infrequent Access (IA) is suitable for objects that are accessed approximately once or twice a month. IA objects have a minimum storage duration of 30 days. You are charged for data retrieval when you access IA objects.
- Archive: Archive is suitable for objects that are rarely accessed. Archive objects have a minimum storage duration of 60 days. Before you can access an Archive object, you must restore the object. The restoration requires approximately 1 minute. You are charged for data retrieval when you restore an Archive object.
- Cold Archive: Cold Archive is suitable for long-term storage of backup objects and raw data. Cold Archive objects have a minimum storage duration of 180 days. Before you can access a Cold Archive object, you must restore the object. The amount of time required to restore a Cold Archive object varies based on the data size and the restore mode of the object. You are charged for data retrieval when you restore a Cold Archive object.
For more information, see Overview.
Encryption Method Specify the server-side encryption method for the object. - Inherited from Bucket: The encryption method of the object is the same as that of the bucket.
- OSS-Managed: The keys managed by OSS are used to encrypt objects in the bucket. OSS uses keys to encrypt objects. OSS also uses regularly rotated master keys to encrypt cryptographic keys.
- KMS: The default customer master key (CMK) stored in Key Management Service (KMS) or a specific CMK is used to encrypt and decrypt data. The encryption key of KMS contains the following elements:
- alias/acs/oss: The default CMK stored in KMS is used to encrypt different objects and decrypt objects when the objects are downloaded.
- CMK ID: The keys generated by a specific CMK are used to encrypt different objects and the specific CMK ID is recorded in the metadata of objects. Objects are decrypted when they are downloaded by users who have the decryption permissions. Before you specify a CMK ID, you must create a normal key or an external key in the same region as the bucket in the KMS console.
- Encryption Algorithm: Only AES-256 is supported.
User Metadata Add user metadata. You can add multiple pieces of user metadata as custom headers. However, the total size of the user metadata cannot exceed 8 KB. When you add user metadata, the user metadata headers must be prefixed with x-oss-meta-
and assigned values. Example: x-oss-meta-location:hangzhou.
- Configure the basic settings. The following table describes the parameters.
- Click Upload.
You can view the upload progress of objects on the Upload Tasks tab.
Use OSS SDKs
The following sample code provides examples on how to perform simple upload to upload an object to a versioning-enabled bucket by using OSS SDKs for common programming languages. For more information about how to perform simple upload to upload an object to a versioning-enabled bucket by using OSS SDKs for other programming languages, see Overview.
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.*;
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";
// Security risks may arise if you use the AccessKey pair of an Alibaba Cloud account to access OSS because the account has permissions on all API operations. We recommend that you use a Resource Access Management (RAM) user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console.
String accessKeyId = "yourAccessKeyId";
String accessKeySecret = "yourAccessKeySecret";
// Specify the name of the bucket. Example: examplebucket.
String bucketName = "examplebucket";
// Specify the full path of the object. The full path of the object cannot contain the bucket name.
String objectName = "exampledir/object";
// Create an OSSClient instance.
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
try {
// Upload a string to the object in this example.
String content = "Hello OSS";
PutObjectResult result = ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(content.getBytes()));
// Query the version ID of the object.
System.out.println("result.versionid: " + result.getVersionId());
} 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();
}
}
}
}
<?php
if (is_file(__DIR__ . '/../autoload.php')) {
require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
require_once __DIR__ . '/../vendor/autoload.php';
}
use OSS\OssClient;
use OSS\Core\OssException;
// The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console.
$accessKeyId = "<yourAccessKeyId>";
$accessKeySecret = "<yourAccessKeySecret>";
// In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint.
$endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
$bucket= "<yourBucketName>";
// Specify the full path of the object. Do not include the bucket name in the full path. Example: example/test.txt.
$object = "<yourObjectName>";
$content = "hello world";
$ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
try {
// Upload the object to the versioning-enabled bucket.
$ret = $ossClient->putObject($bucket, $object, $content);
// Display the version ID of the uploaded object.
print("versionId:" .$ret[OssClient::OSS_HEADER_VERSION_ID]);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
const OSS = require('ali-oss');
const client = new OSS({
// 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 oss-cn-hangzhou.
region: 'yourregion',
// The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console.
accessKeyId: 'yourAccessKeyId',
accessKeySecret: 'yourAccessKeySecret',
// Set yourbucketname to the name of your bucket.
bucket: 'yourbucketname'
});
async function put() {
const result = await client.put('fileName', 'file');
console.log(result.res.headers['x-oss-version-id']); // View the version ID of the uploaded object.
}
put();
# -*- coding: utf-8 -*-
import oss2
# The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console.
auth = oss2.Auth('yourAccessKeyId', 'yourAccessKeySecret')
# Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
# Specify the name of the bucket.
bucket = oss2.Bucket(auth, 'https://oss-cn-hangzhou.aliyuncs.com', 'yourBucketName')
# Upload the object.
result = bucket.put_object('yourObjectName', 'content of object')
# Display the returned HTTP status code.
print('http response code: {0}'.format(result.status))
# Display the version ID of the uploaded object.
print('put object version:', result.versionid)
using System.Text;
using Aliyun.OSS;
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
var endpoint = "yourEndpoint";
// The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console.
var accessKeyId = "yourAccessKeyId";
var accessKeySecret = "yourAccessKeySecret";
// Specify the name of the bucket. Example: examplebucket.
var bucketName = "examplebucket";
// Specify the full path of the object. The full path of the object cannot contain the bucket name. Example: exampledir/exampleobject.txt.
var objectName = "exampleobject.txt";
var objectContent = "More than just cloud.";
// Create an OSSClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
try
{
byte[] binaryData = Encoding.ASCII.GetBytes(objectContent);
MemoryStream requestContent = new MemoryStream(binaryData);
// Upload the object.
var result = client.PutObject(bucketName, objectName, requestContent);
Console.WriteLine("Put object succeeded versionid : {0}", result.VersionId);
}
catch (Exception ex)
{
Console.WriteLine("Put object failed, {0}", ex.Message);
}
package main
import (
"fmt"
"net/http"
"os"
"strings"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
func main() {
// Create an OSSClient instance.
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint.
// The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console.
client, err := oss.New("yourEndpoint", "yourAccessKeyId", "yourAccessKeySecret")
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Specify the name of the bucket.
bucket, err := client.Bucket("yourBucketName")
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
var retHeader http.Header
// Upload the string. Use oss.GetResponseHeader to obtain the returned header.
// Set yourObjectName to the full path of the object. Do not include the bucket name in the full path.
err = bucket.PutObject("yourObjectName", strings.NewReader("yourObjectValue"), oss.GetResponseHeader(&retHeader))
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Display the value of x-oss-version-id.
fmt.Println("x-oss-version-id:", oss.GetVersionId(retHeader))
}
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;
int main(void)
{
/* Initialize information about the account that is used to access OSS. */
/* The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. */
std::string AccessKeyId = "yourAccessKeyId";
std::string AccessKeySecret = "yourAccessKeySecret";
/* Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
std::string Endpoint = "yourEndpoint";
/* Specify the name of the bucket. Example: examplebucket. */
std::string BucketName = "examplebucket";
/* Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt. */
std::string ObjectName = "exampledir/exampleobject.txt";
/* Initialize resources, such as network resources. */
InitializeSdk();
ClientConfiguration conf;
OssClient client(Endpoint, AccessKeyId, AccessKeySecret, conf);
std::shared_ptr<std::iostream> content = std::make_shared<std::stringstream>();
*content << "test cpp sdk";
PutObjectRequest request(BucketName, ObjectName, content);
/* Upload the object. */
auto outcome = client.PutObject(request);
if (outcome.isSuccess()) {
std::cout << "versionid:" << outcome.result().VersionId() << std::endl;
}
else {
/* Handle exceptions. */
std::cout << "PutObject fail" <<
",code:" << outcome.error().Code() <<
",message:" << outcome.error().Message() <<
",requestId:" << outcome.error().RequestId() << std::endl;
return -1;
}
/* Release resources, such as network resources. */
ShutdownSdk();
return 0;
}
Use ossutil
For more information about how to perform simple upload to upload an object to a versioning-enabled bucket by using ossutil, see Upload objects.
Use RESTful APIs
If your business requires a high level of customization, you can directly call RESTful APIs. To directly call an API, you must include the signature calculation in your code. For more information, see PutObject.
List objects
You can call the GetBucketVersions (ListObjectVersions) operation to obtain information about all object versions in a versioning-enabled bucket, including delete markers.
- Compared with the GetBucketVersions (ListObjectVersions) operation, the GetBucket (ListObject) operation returns only the current object versions that are not delete markers in a bucket.
- Up to 1,000 object versions can be returned for a single GetBucketVersions (ListObjectVersions) request. You can send multiple GetBucketVersions (ListObjectVersions) requests to obtain all object versions in a versioning-enabled bucket.
For example, a bucket contains two objects whose keys are example.jpg and photo.jpg. The example.jpg object has 900 versions. The photo.jpg object has 500 versions. If you send a GetBucketVersions (ListObjectVersions) request, 900 versions of the example.jpg object and 100 versions of the photo.jpg object are returned. The versions are returned in alphabetical order of object keys first and then in the order of time when the versions are generated.
All object versions including delete markers are returned when the GetBucketVersions (ListObjectVersions) operation is called, as shown in the following figure. Only current object versions that are not delete markers are returned when the GetBucket(ListObject) operation is called. Therefore, only the current version of the photo.jpg object, whose version ID is 444444, is returned.

Use the OSS console
- Log on to the OSS console.
- In the left-side navigation pane, click Buckets. On the Buckets page, click the name of the bucket whose objects you want to list.
The current page displays different versions of all objects in the bucket, including delete markers.
Use OSS SDKs
The following code provides examples on how to list objects in a versioning-enabled bucket by using OSS SDKs for common programming languages. For more information about how to list objects by using OSS SDKs for other programming languages, see Overview.
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.*;
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";
// The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console.
String accessKeyId = "yourAccessKeyId";
String accessKeySecret = "yourAccessKeySecret";
// Specify the name of the bucket. Example: examplebucket.
String bucketName = "examplebucket";
// Create an OSSClient instance.
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
try {
// List the versions of all objects including delete markers in the bucket.
String nextKeyMarker = null;
String nextVersionMarker = null;
VersionListing versionListing = null;
do {
ListVersionsRequest listVersionsRequest = new ListVersionsRequest()
.withBucketName(bucketName)
.withKeyMarker(nextKeyMarker)
.withVersionIdMarker(nextVersionMarker);
versionListing = ossClient.listVersions(listVersionsRequest);
for (OSSVersionSummary ossVersion : versionListing.getVersionSummaries()) {
System.out.println("key name: " + ossVersion.getKey());
System.out.println("versionid: " + ossVersion.getVersionId());
System.out.println("Is latest: " + ossVersion.isLatest());
System.out.println("Is delete marker: " + ossVersion.isDeleteMarker());
}
nextKeyMarker = versionListing.getNextKeyMarker();
nextVersionMarker = versionListing.getNextVersionIdMarker();
} while (versionListing.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();
}
}
}
}
<?php
if (is_file(__DIR__ . '/../autoload.php')) {
require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
require_once __DIR__ . '/../vendor/autoload.php';
}
use OSS\OssClient;
use OSS\Core\OssException;
// Security risks may arise if you use the AccessKey pair of an Alibaba Cloud account to access Object Storage Service (OSS) because the account has permissions on all API operations. We recommend that you use a Resource Access Management (RAM) user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console.
$accessKeyId = "yourAccessKeyId";
$accessKeySecret = "yourAccessKeySecret";
// Set yourEndpoint to the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set yourEndpoint to https://oss-cn-hangzhou.aliyuncs.com.
$endpoint = "yourEndpoint";
// Specify the name of the bucket. Example: examplebucket.
$bucket= "examplebucket";
$ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint, false);
try{
$option = array(
OssClient::OSS_KEY_MARKER => null,
OssClient::OSS_VERSION_ID_MARKER => null
);
$bool = true;
while ($bool){
$result = $ossClient->listObjectVersions($bucket,$option);
// Display the information about the versions of the listed objects.
foreach ($result->getObjectVersionList() as $key => $info){
printf("key name: {$info->getKey()}\n");
printf("versionid: {$info->getVersionId()}\n");
printf("Is latest: {$info->getIsLatest()}\n\n");
}
// Display the version information of the listed delete markers.
foreach ($result->getDeleteMarkerList() as $key => $info){
printf("del_maker key name: {$info->getKey()}\n");
printf("del_maker versionid: {$info->getVersionId()}\n");
printf("del_maker Is latest: {$info->getIsLatest()}\n\n");
}
if($result->getIsTruncated() === 'true'){
$option[OssClient::OSS_KEY_MARKER] = $result->getNextKeyMarker();
$option[OssClient::OSS_VERSION_ID_MARKER] = $result->getNextVersionIdMarker();
}else{
$bool = false;
}
}
} catch(OssException $e) {
printf($e->getMessage() . "\n");
return;
}
// The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in Object Storage Service (OSS) is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console.
const accessKeyId = "yourAccessKeyId";
const accessKeySecret = "yourAccessKeySecret";
// In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint.
const endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Set yourbucketname to the name of your bucket.
const bucket = "yourbucketname";
// Create an OSSClient instance.
const ossClient = new OSS({
accessKeyId,
accessKeySecret,
endpoint,
bucket
});
// List the versions of all objects including delete markers in the bucket.
async function main () {
let nextKeyMarker = null;
let nextVersionMarker = null;
let versionListing = null;
do {
versionListing = await client.getBucketVersions({
keyMarker: nextKeyMarker,
versionIdMarker: nextVersionMarker
})
versionListing.objects.forEach(o => {
console.log(`${o.name}, ${o.versionId}`)
})
versionListing.deleteMarker.forEach(o => {
console.log(`${o.name}, ${o.versionId}`)
})
nextKeyMarker = versionListing.NextKeyMarker;
nextVersionMarker = versionListing.NextVersionIdMarker;
} while (versionListing.isTruncated);
}
main()
# -*- coding: utf-8 -*-
import oss2
# The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console.
auth = oss2.Auth('yourAccessKeyId', 'yourAccessKeySecret')
# Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
# Specify the name of the bucket.
bucket = oss2.Bucket(auth, 'https://oss-cn-hangzhou.aliyuncs.com', 'yourBucketName')
# Call the list_object_versions operation to list the versions of objects in a versioning-enabled bucket.
# List the versions of all objects including delete markers in the bucket.
result = bucket.list_object_versions()
# List the versions of all objects in the bucket.
next_key_marker = None
next_versionid_marker = None
while True:
result = bucket.list_object_versions(key_marker=next_key_marker, versionid_marker=next_versionid_marker)
# Display the versions of the listed objects.
for version_info in result.versions:
print('version_info.versionid:', version_info.versionid)
print('version_info.key:', version_info.key)
print('version_info.is_latest:', version_info.is_latest)
# Display the versions of the listed delete markers.
for del_maker_Info in result.delete_marker:
print('del_maker.key:', del_maker_Info.key)
print('del_maker.versionid:', del_maker_Info.versionid)
print('del_maker.is_latest:', del_maker_Info.is_latest)
is_truncated = result.is_truncated
# Check whether all versions of all objects in the bucket are listed. If all versions of all objects are incompletely listed, the list operation continues. If all versions of all objects are completely listed, the list operation stops.
if is_truncated:
next_key_marker = result.next_key_marker
next_versionid_marker = result.next_versionid_marker
else:
break
package main
import (
"fmt"
"os"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
func HandleError(err error) {
fmt.Println("Error:", err)
os.Exit(-1)
}
func main() {
// Create an OSSClient instance.
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
// The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console.
client, err := oss.New("yourEndpoint","yourAccessKeyId","yourAccessKeySecret")
if err != nil {
HandleError(err)
}
// Specify the name of the bucket.
bucketName := "examplebucket"
bucket,err := client.Bucket(bucketName)
if err != nil {
HandleError(err)
}
// List the versions of all objects including delete markers in the bucket.
keyMarker := oss.KeyMarker("")
// The VersionIdMarker parameter is configured together with the KeyMarker parameter to specify the position from which the list operation starts.
versionIdMarker := oss.VersionIdMarker("")
for {
lor, err := bucket.ListObjectVersions(keyMarker,versionIdMarker)
if err != nil {
HandleError(err)
}
// Display the version IDs of the objects.
for _, dirName := range lor.ObjectVersions{
fmt.Println("Versionid:",dirName.VersionId)
fmt.Println("Key:",dirName.Key)
fmt.Println("Is Latest",dirName.IsLatest)
}
// Display the versions of the listed delete markers.
for _, marker := range lor.ObjectDeleteMarkers {
fmt.Println(marker.VersionId)
fmt.Println(marker.Key)
}
// Check whether the required versions are listed. If the versions are incompletely listed, the list operation continues. If the versions are completely listed, the list operation stops.
keyMarker = oss.KeyMarker(lor.NextKeyMarker)
versionIdMarker = oss.VersionIdMarker(lor.NextVersionIdMarker)
if !lor.IsTruncated {
break
}
}
}
Use ossutil
For more information about how to list objects in a versioning-enabled bucket, see List objects.
Use RESTful APIs
If your business requires a high level of customization, you can directly call RESTful APIs. To directly call an API, you must include the signature calculation in your code. For more information, see ListObjectVersions (GetBucketVersions).
Download objects
You can download the current version or a specific version of an object from a versioning-enabled bucket.
By default, if a GetObject request in which no version ID is specified is initiated to download an object, the current version of the object is returned. The current version of the object whose version ID is 333333, is returned, as shown in the following figure.

If a GetRequest request in which the no version ID is specified is initiated to download an object and the current version of the object is a delete marker, 404 Not Found is returned.

To download a specific version of an object, you must specify the version ID in the GetObject request. A GetObject request in which the version ID 222222 is specified is initiated to download the object whose version ID is 222222, as shown in the following figure.

Use the OSS console
- Log on to the OSS console.
- In the left-side navigation pane, click Buckets. On the Buckets page, click the name of the desired bucket.
- In the left-side navigation tree, choose .
- Click the version that you want to download. In the View Details panel, click Download below the object URL in the URL field.
Use OSS SDKs
The following code provides examples on how to download objects from a versioning-enabled bucket by using OSS SDKs for common programming languages. For more information about how to download objects by using OSS SDKs for other programming languages, see Overview.
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Demo {
public static void main(String[] args) {
// In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint.
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console.
String accessKeyId = "yourAccessKeyId";
String accessKeySecret = "yourAccessKeySecret";
// Specify the name of the bucket. Example: examplebucket.
String bucketName = "examplebucket";
// Specify the full path of the object. Example: exampledir/exampleobject.txt. The full path of the object cannot contain the bucket name.
String objectName = "exampledir/exampleobject.txt";
// Specify the version ID of the object. Example: CAEQARiBgID8rumR2hYiIGUyOTAyZGY2MzU5MjQ5ZjlhYzQzZjNlYTAyZDE3****.
String versionid = "CAEQARiBgID8rumR2hYiIGUyOTAyZGY2MzU5MjQ5ZjlhYzQzZjNlYTAyZDE3****";
// Create an OSSClient instance.
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
try {
// Encapsulate the GetObject request.
GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, objectName);
getObjectRequest.setVersionId(versionid);
// ossObject specifies the bucket name, object name, object metadata, and an input stream.
OSSObject ossObject = ossClient.getObject(getObjectRequest);
// View the version ID of the downloaded object.
System.out.println("Get Object versionid:" + ossObject.getObjectMetadata().getVersionId());
// View the content of the object that has the specified version ID.
System.out.println("Object content:");
BufferedReader reader = new BufferedReader(new InputStreamReader(ossObject.getObjectContent()));
while (true) {
String line = reader.readLine();
if (line == null) break;
System.out.println("\n" + line);
}
} 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 (Throwable 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 {
// Shut down the OSSClient instance.
if (ossClient != null) {
ossClient.shutdown();
}
}
}
}
<?php
if (is_file(__DIR__ . '/../autoload.php')) {
require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
require_once __DIR__ . '/../vendor/autoload.php';
}
use OSS\OssClient;
use OSS\Core\OssException;
// The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console.
$accessKeyId = "<yourAccessKeyId>";
$accessKeySecret = "<yourAccessKeySecret>";
// In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint.
$endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
$bucket= "<yourBucketName>";
// Specify the full path of the object. Do not include the bucket name in the full path. Example: example/test.txt.
$object = "<yourObjectName>";
// Specify the version ID of the object.
$versionId = "<yourObjectVersionId>";
$ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
try{
// Download the specific version of the object.
$content = $ossClient->getObject($bucket, $object, array(OssClient::OSS_VERSION_ID => $versionId));
print($content);
} catch(OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
const OSS = require('ali-oss');
const client = new OSS({
// 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 oss-cn-hangzhou.
region: 'yourregion',
// The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console.
accessKeyId: 'yourAccessKeyId',
accessKeySecret: 'yourAccessKeySecret',
// Specify the name of the bucket.
bucket: 'yourbucketname'
});
async function get() {
const get = await client.get(name, {
// Display the version ID of the downloaded object.
versionId: 'versionId',
});
console.log(result.content);
}
get();
# -*- coding: utf-8 -*-
import oss2
# The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console.
auth = oss2.Auth('yourAccessKeyId', 'yourAccessKeySecret')
# Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
# Set yourBucketName to the name of your bucket.
bucket = oss2.Bucket(auth, 'https://oss-cn-hangzhou.aliyuncs.com', 'yourBucketName')
# Download a specified version of the object.
params = dict()
params['versionId'] = '<yourObjectVersionId>'
object_stream = bucket.get_object('<yourObjectName>', params=params)
# Read the content of the downloaded object.
read_content = object_stream.read()
print('get object content:', read_content)
# Display the version ID of the downloaded object.
print('get object versionid:', object_stream.versionid)
# You must call read() to read the object from the stream returned by get_object before you can calculate the CRC-64 checksum of the object.
if object_stream.client_crc != object_stream.server_crc:
print "The CRC checksum between client and server is inconsistent!"
using Aliyun.OSS;
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
var endpoint = "yourEndpoint";
// The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console.
var accessKeyId = "yourAccessKeyId";
var accessKeySecret = "yourAccessKeySecret";
// Specify the name of the bucket. Example: examplebucket.
var bucketName = "examplebucket";
// Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt.
var objectName = "exampledir/exampleobject.txt";
// Specify the full path of the local file. Example: D:\\localpath\\examplefile.txt.
var downloadFilename = "D:\\localpath\\examplefile.txt";
var versionid = "yourArchiveObjectVersionid";
// Create an OSSClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
try
{
// Download the object to a stream. OssObject includes object information such as the bucket in which the object is stored, the object name, object metadata, and an input stream.
var request = new GetObjectRequest(bucketName, objectName)
{
// Specify the version ID of the object.
VersionId = versionid
};
var obj = client.GetObject(request);
using (var requestStream = obj.Content)
{
byte[] buf = new byte[1024];
var fs = File.Open(downloadFilename, FileMode.OpenOrCreate);
var len = 0;
// The input stream can be used to read and download the object content to a local file or to the memory.
while ((len = requestStream.Read(buf, 0, 1024)) != 0)
{
fs.Write(buf, 0, len);
}
fs.Close();
}
Console.WriteLine("Get object succeeded, vesionid:{0}", obj.VersionId);
}
catch (Exception ex)
{
Console.WriteLine("Get object failed. {0}", ex.Message);
}
package main
import (
"fmt"
"net/http"
"os"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
func main() {
// Create an OSSClient instance.
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint.
// The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console.
client, err := oss.New("yourEndpoint", "yourAccessKeyId", "yourAccessKeySecret")
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Specify the name of the bucket.
bucket, err := client.Bucket("<yourBucketName>")
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
var retHeader http.Header
// Download the specified version to the cache.
// Set yourObjectName to the full path of the object. The full path cannot contain the bucket name.
_, err = bucket.GetObject("youObjectName", oss.VersionId("yourObjectVersionId"), oss.GetResponseHeader(&retHeader))
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Display the value of x-oss-version-id.
fmt.Println("x-oss-version-id:", oss.GetVersionId(retHeader))
}
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;
int main(void)
{
/* Initialize the information about the account that is used to access OSS. */
/* The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. */
std::string AccessKeyId = "yourAccessKeyId";
std::string AccessKeySecret = "yourAccessKeySecret";
/* Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
std::string Endpoint = "yourEndpoint";
/* Specify the name of the bucket. Example: examplebucket. */
std::string BucketName = "examplebucket";
/* Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt. */
std::string ObjectName = "exampledir/exampleobject.txt";
/* Initialize resources, such as network resources. */
InitializeSdk();
ClientConfiguration conf;
OssClient client(Endpoint, AccessKeyId, AccessKeySecret, conf);
/* Download the object to local memory. */
GetObjectRequest request(BucketName, ObjectName);
request.setVersionId("yourObjectVersionId");
auto outcome = client.GetObject(request);
if (outcome.isSuccess()) {
std::cout << "getObjectToBuffer" << " success, Content-Length:" << outcome.result().Metadata().ContentLength() << std::endl;
/* Read the content of the downloaded object. */
std::string content;
*(outcome.result().Content()) >> content;
std::cout << "getObjectToBuffer" << "content:" << content << std::endl;
/* Display the version ID of the downloaded object. */
std::cout << "versionid:" << outcome.result().VersionId() << std::endl;
}
else {
/* Handle exceptions. */
std::cout << "getObjectToBuffer fail" <<
",code:" << outcome.error().Code() <<
",message:" << outcome.error().Message() <<
",requestId:" << outcome.error().RequestId() << std::endl;
return -1;
}
/* Release resources, such as network resources. */
ShutdownSdk();
return 0;
}
Use ossutil
For more information about how to download objects from a versioning-enabled bucket by using ossutil, see Download objects.
Use RESTful APIs
If your business requires a high level of customization, you can directly call RESTful APIs. To directly call an API, you must include the signature calculation in your code. For more information, see GetObject.
Delete objects
You can specify a version ID of an object in the DeleteObject request or configure lifecycle rules to permanently delete a version of an object in a versioning-enabled bucket. If you do not specify a version ID of an object in the DeleteObject request, OSS adds a delete marker as the current version of the object.
- By default, if you do not specify a version ID in the DeleteObject request, the current version and previous versions of the object are not deleted.
Do not enable OSS-HDFS and versioning for a bucket.
If OSS-HDFS and versioning are enabled for a bucket, OSS-HDFS may be unavailable. To ensure the stability of OSS-HDFS, you need to suspend versioning at the earliest opportunity and configure lifecycle rules to remove delete markers.
For more information, see What do I do if I enable OSS-HDFS and versioning for a bucket?
In addition, you can specify the Expiration element in lifecycle rules to delete the expired current version of objects in a versioning-enabled bucket. You can also specify the NoncurrentVersionExpiration element in lifecycle rules to permanently delete the expired previous versions of objects in a versioning-enabled bucket. The two elements have the following differences:
- The Expiration element is specified in lifecycle rules to delete the expired current version of objects. When an object is deleted based on a lifecycle rule in which the Expiration element is specified, OSS stores the current version of the object as a previous version and adds a delete marker as the new current version of the object.
- The NoncurrentVersionExpiration element is specified in lifecycle rules to delete expired previous versions of objects. A previous version deleted based on a lifecycle rule in which the NoncurrentVersionExpiration element is specified is permanently deleted and cannot be restored.
For more information about how to use versioning with lifecycle rules, see Configuration elements.
The following section describes how OSS deletes an object when the version ID is specified and not specified in the DeleteObject request.
- If the version ID is not specified in the DeleteObject request, OSS adds a delete marker as the current version of the object to be deleted. The delete marker has a unique version ID but does not have data and ACL. A delete marker with the version ID 444444 is added as the current version, as shown in the following figure.
- If the version ID is specified in the DeleteObject request, the specified version is permanently deleted. The version whose ID is 333333 is permanently deleted, as shown in the following figure.
Use the OSS console
To minimize storage costs, we recommend that you delete the previous versions of objects that you no longer need at your earliest opportunity.
- Log on to the OSS console.
- In the left-side navigation pane, click Buckets. On the Buckets page, click the name of the desired bucket.
- In the left-side navigation tree, choose .
- Click Permanently Delete in the Actions column that corresponds to the previous version you want to delete.
To delete multiple previous versions of an object, select the previous versions that you want to delete and choose
. - Click OK.
You can also configure lifecycle rules to allow OSS to periodically delete previous versions. For more information, see Overview.
Use OSS SDKs
The following code provides examples on how to delete a specific version of an object from a versioning-enabled bucket by using OSS SDKs for common programming languages. For more information about how to delete a specific version of an object by using OSS SDKs for other programming languages, see Overview.
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
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";
// The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console.
String accessKeyId = "yourAccessKeyId";
String accessKeySecret = "yourAccessKeySecret";
// Specify the bucket name. Example: examplebucket.
String bucketName = "examplebucket";
// Specify the full path of the object. The full path of the object cannot contain the bucket name.
String objectName = "exampledir/object";
String versionId = "CAEQMxiBgICAof2D0BYiIDJhMGE3N2M1YTI1NDQzOGY5NTkyNTI3MGYyMzJm****";
// Create an OSSClient instance.
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
try {
// Delete the object that has the specified version ID.
ossClient.deleteVersion(bucketName, objectName , versionId);
} 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();
}
}
}
}
<?php
if (is_file(__DIR__ . '/../autoload.php')) {
require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
require_once __DIR__ . '/../vendor/autoload.php';
}
use OSS\OssClient;
use OSS\Core\OssException;
// The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console.
$accessKeyId = "<yourAccessKeyId>";
$accessKeySecret = "<yourAccessKeySecret>";
// In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint.
$endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
$bucket= "<yourBucketName>";
// Specify the full path of the object. Do not include the bucket name in the full path. Example: example/test.txt.
$object = "<yourObjectName>";
$versionId = "<yourObjectVersionId>";
$ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
try{
// Delete the object with the specified version ID.
$ossClient->deleteObject($bucket, $object, array(OssClient::OSS_VERSION_ID => $versionId));
} catch(OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
const OSS = require('ali-oss');
const client = new OSS({
// 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 oss-cn-hangzhou.
region: 'yourregion',
// The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console.
accessKeyId: 'yourAccessKeyId',
accessKeySecret: 'yourAccessKeySecret',
// Set yourbucketname to the name of your bucket.
bucket: 'yourbucketname'
});
// Delete the object with the specified version ID.
const versionId = 'yourversionId';
async function deleteVersionObject() {
const result = await client.delete(obj.name, {
versionId
});
}
deleteVersionObject();
# -*- coding: utf-8 -*-
import os
import oss2
# The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console.
auth = oss2.Auth('yourAccessKeyId', 'yourAccessKeySecret')
# Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
# Specify the name of the bucket.
bucket = oss2.Bucket(auth, 'https://oss-cn-hangzhou.aliyuncs.com', 'yourBucketName')
# Specify the full path of the object. Do not include the bucket name in the full path. Example: example/test.txt.
object_name = 'yourObjectName'
# Specify the version ID of the object or delete marker that you want to delete.
params = dict()
params['versionId'] = 'yourObjectVersionIdOrDeleteMarkerVersionId'
# Delete the object with the specific version ID or the object whose current version is a delete marker with the specific version ID.
result = bucket.delete_object(object_name, params=params)
print("delete object name: ", object_name)
# If the version ID of an object is specified in the request, the value of the delete_marker header in the response is None and the value of the versionId header in the response is the version ID specified in the request.
# If the version ID of a delete marker is specified in the request, the value of the delete_marker header in the response is True and the value of the versionId header in the response is the version ID specified in the request.
if result.delete_marker:
print("delete del-marker versionid: ",result.versionid)
else:
print("delete object versionid:", result.versionid)
using Aliyun.OSS;
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
var endpoint = "yourEndpoint";
// The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console.
var accessKeyId = "yourAccessKeyId";
var accessKeySecret = "yourAccessKeySecret";
// Specify the name of the bucket. Example: examplebucket.
var bucketName = "examplebucket";
// Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt.
var objectName = "exampledir/exampleobject.txt";
// Specify the version ID of the object or the delete marker.
var versionid = "yourObjectVersionidOrDelMarkerVersionid";
// Create an OSSClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
try
{
// Specify the version ID of the object or the delete marker that you want to delete.
var request = new DeleteObjectRequest(bucketName, key)
{
VersionId = versionid
};
client.DeleteObject(request);
Console.WriteLine("Delete object succeeded");
}
catch (Exception ex)
{
Console.WriteLine("Delete object failed. {0}", ex.Message);
}
package main
import (
"fmt"
"net/http"
"os"
"strings"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
func main() {
// Create an OSSClient instance.
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint.
// The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console.
client, err := oss.New("yourEndpoint", "yourAccessKeyId", "yourAccessKeySecret")
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Set yourBucketName to the name of the bucket.
bucket, err := client.Bucket("yourBucketName")
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Permanently delete an object by specifying the version ID of the object.
err = bucket.DeleteObject(key, oss.VersionId("yourObjectVersionId"))
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
}
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;
int main(void)
{
/* Initialize the information about the account that is used to access OSS. */
/* The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. */
std::string AccessKeyId = "yourAccessKeyId";
std::string AccessKeySecret = "yourAccessKeySecret";
/* Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
std::string Endpoint = "yourEndpoint";
/* Specify the name of the bucket. Example: examplebucket. */
std::string BucketName = "examplebucket";
/* Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt. */
std::string ObjectName = "exampledir/exampleobject.txt";
/* Initialize resources, such as network resources. */
InitializeSdk();
ClientConfiguration conf;
OssClient client(Endpoint, AccessKeyId, AccessKeySecret, conf);
/* Delete the object with the specified version ID or the object whose current version is a delete marker with the specified version ID. */
auto outcome = client.DeleteObject(DeleteObjectRequest(BucketName, ObjectName, "yourObjectVersionIdOrDeleteMarkerVersionId"));
/* If the version ID of an object is specified in the request, the value of the delete_marker header in the response is None and the value of the versionId header in the response is the version ID specified in the request. */
/* If the version ID of a delete marker is specified in the request, the value of the delete_marker header in the response is True and the value of the versionId header in the response is the version ID specified in the request. */
if (!outcome.isSuccess()) {
/* Handle exceptions. */
std::cout << "DeleteObject fail" <<
",code:" << outcome.error().Code() <<
",message:" << outcome.error().Message() <<
",requestId:" << outcome.error().RequestId() << std::endl;
return -1;
}
/* Release resources, such as network resources. */
ShutdownSdk();
return 0;
}
Use ossutil
For more information about how to delete objects from a versioning-enabled bucket by using ossutil, see Delete objects.
Use RESTful APIs
If your business requires a high level of customization, you can directly call RESTful APIs. To directly call an API, you must include the signature calculation in your code. For more information, see DeleteObject.
Restore objects
When versioning is enabled for a bucket, all versions of objects in the bucket are retained. You can restore a specific previous version of an object as the current version.
- Call the CopyObject operation to copy the previous version of an object to the same bucket
The copied previous version becomes the current version of the object, and all versions of the object are retained.
A previous version whose ID is 222222 is copied to the same bucket, as shown in the following figure. OSS generates a new version ID 444444 for the copied version. The copied version becomes the current version of the object. As a result, the object has two versions that have the same content: 222222 and 444444. Version 222222 is the previous version and version 444444 is the current version. - Permanently delete the current version of an object
The current version whose ID is 222222 is permanently deleted by using a DeleteObject request in which the version ID is specified, as shown in the following figure. The most recent previous version whose ID is 111111 becomes the current version of the object.
Use the OSS console
- Log on to the OSS console.
- In the left-side navigation pane, click Buckets. On the Buckets page, click the name of the desired bucket.
- In the left-side navigation tree, choose .
- Restore a specific previous version of an object as the current version. Important You can restore only one previous version of an object at a time. The previous version that you want to restore cannot be a delete marker.
- Restore the previous version of an object
Click Restore in the Actions column that corresponds to the previous version that you want to restore.
- Restore the previous versions of multiple objects
Select the previous versions that you want to restore and choose
.
- Restore the previous version of an object
Use OSS SDKs
The following code provides examples on how to copy a specific version of an object from a versioning-enabled bucket by using OSS SDKs for common programming languages. For more information about how to copy a specific version of an object by using OSS SDKs for other programming languages, see Overview.
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.*;
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";
// The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console.
String accessKeyId = "yourAccessKeyId";
String accessKeySecret = "yourAccessKeySecret";
// Specify the name of the source bucket.
String sourceBucketName = "srcexamplebucket";
// Specify the full path of the source object. The full path of the object cannot contain the bucket name.
String sourceObjectName = "srcexampleobject.txt";
// Specify the name of the destination bucket. The destination bucket must be in the same region as the source bucket.
String destinationBucketName = "desexamplebucket";
// Specify the full path of the destination object. The full path of the object cannot contain the bucket name.
String destinationObjectName = "desexampleobject.txt";
String versionId = "CAEQMxiBgICAof2D0BYiIDJhMGE3N2M1YTI1NDQzOGY5NTkyNTI3MGYyMzJm****";
// Create an OSSClient instance.
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
try {
CopyObjectRequest copyObjectRequest = new CopyObjectRequest(sourceBucketName, sourceObjectName, destinationBucketName, destinationObjectName);
copyObjectRequest.setSourceVersionId(versionId);
CopyObjectResult copyObjectResult = ossClient.copyObject(copyObjectRequest);
System.out.println("ETag: " + copyObjectResult.getETag() + " LastModified: " + copyObjectResult.getLastModified());
System.out.println("dest object versionid: " + copyObjectResult.getVersionId());
} 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();
}
}
}
}
<?php
if (is_file(__DIR__ . '/../autoload.php')) {
require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
require_once __DIR__ . '/../vendor/autoload.php';
}
use OSS\OssClient;
use OSS\Core\OssException;
// The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console.
$accessKeyId = "<yourAccessKeyId>";
$accessKeySecret = "<yourAccessKeySecret>";
// In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint.
$endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
$bucket= "<yourBucketName>";
// Specify the full path of the object. Do not include the bucket name in the full path. Example: example/test.txt.
$object = "<yourObjectName>";
$versionId = "<yourObjectVersionId>";
$to_bucket = $bucket;
$to_object = $object . '.copy';
$ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
try{
// Copy the object with the specified version ID.
$ret = $ossClient->copyObject($bucket, $object, $to_bucket, $to_object, array(OssClient::OSS_VERSION_ID => $versionId));
print("versionId:" .$ret['x-oss-version-id']);
} catch(OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
const OSS = require('ali-oss');
const client = new OSS({
// 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 oss-cn-hangzhou.
region: 'yourregion',
// The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console.
accessKeyId: 'yourAccessKeyId',
accessKeySecret: 'yourAccessKeySecret',
// Set yourbucketname to the name of your bucket.
bucket: 'yourbucketname'
});
// Specify the version ID of the object to copy.
const versionId = 'your versionId';
async function copy() {
const result = await client.copy(target, origin, { versionId });
console.log(result.res.headers);
}
copy();
# -*- coding: utf-8 -*-
import oss2
# The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console.
auth = oss2.Auth('yourAccessKeyId', 'yourAccessKeySecret')
# Specify the name of the source bucket. Example: srcexamplebucket.
src_bucket_name = 'srcexamplebucket'
# Specify the name of the destination bucket. The destination bucket must be in the same region as the source bucket. Example: destexamplebucket.
# If you copy an object within a bucket, make sure that you specify the same bucket name for the source and destination buckets.
dest_bucket_name = 'destexamplebucket'
# Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
bucket = oss2.Bucket(auth, 'yourEndpoint', dest_bucket_name)
# Specify the full path of the source object. The full path of the object cannot contain the bucket name. Example: exampledir/exampleobject.txt.
src_object_name = 'srcexampledir/exampleobject.txt'
# Specify the full path of the destination object. The full path cannot contain the bucket name. Example: exampledir/exampleobject.txt.
dest_object_name = 'destexampledir/exampleobject.txt'
# Specify the version ID of the source object.
versionId = 'CAEQMxiBgICAof2D0BYiIDJhMGE3N2M1YTI1NDQzOGY5NTkyNTI3MGYyMzJm****'
# Copy the specified version of the source object.
params = dict()
params['versionId'] = versionId
# Copy the source object from the source bucket to the destination bucket.
result = bucket.copy_object(src_bucket_name, src_object_name, dest_object_name, params=params)
# Display the response. If the returned value is 200, the source object is copied to the destination bucket.
print('result.status:', result.status)
using Aliyun.OSS;
using Aliyun.OSS.Common;
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
var endpoint = "yourEndpoint";
// The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console.
var accessKeyId = "yourAccessKeyId";
var accessKeySecret = "yourAccessKeySecret";
// Specify the name of the source bucket.
var sourceBucket = "yourSourceBucketName";
// Specify the full path of the source object. Do not include the bucket name in the full path of the object.
var sourceObject = "yourSourceObjectName";
// Specify the name of the destination bucket. The destination bucket must be in the same region as the source bucket.
var targetBucket = "yourDestBucketName";
// Specify the full path of the destination object. Do not include the bucket name in the full path of the object.
var targetObject = "yourDestObjectName";
// Specify the version ID of the object.
var versionid = "yourArchiveObjectVersionid";
// Create an OSSClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
try
{
var metadata = new ObjectMetadata();
metadata.AddHeader("mk1", "mv1");
metadata.AddHeader("mk2", "mv2");
var req = new CopyObjectRequest(sourceBucket, sourceObject, targetBucket, targetObject)
{
// If the value of NewObjectMetadata is null, the COPY mode is used and the metadata of the source object is copied to the destination object. If the value of NewObjectMetadata is not null, the REPLACE mode is used and the metadata of the source object overwrites the metadata of the destination object.
NewObjectMetadata = metadata,
// Specify the version ID of the object.
SourceVersionId = versionid
};
// Copy the object.
var result = client.CopyObject(req);
Console.WriteLine("Copy object succeeded, vesionid:{0}", result.VersionId);
}
catch (OssException ex)
{
Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID: {2} \tHostID: {3}",
ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
}
catch (Exception ex)
{
Console.WriteLine("Failed with error info: {0}", ex.Message);
}
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;
int main(void)
{
/* Initialize information about the account that is used to access OSS. */
/* The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. */
std::string AccessKeyId = "yourAccessKeyId";
std::string AccessKeySecret = "yourAccessKeySecret";
/* Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
std::string Endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
/* Specify the name of the source bucket. Example: srcexamplebucket. */
std::string SourceBucketName = "srcexamplebucket";
/* Specify the name of the destination bucket. The destination bucket must be located in the same region as the source bucket. Example: destbucket. */
std::string CopyBucketName = "destbucket";
/* Specify the full path of the source object. Do not include the bucket name in the full path. Example: srcdir/scrobject.txt. */
std::string SourceObjectName = "srcdir/scrobject.txt";
/* Specify the full path of the destination object. Do not include the bucket name in the full path. Example: destdir/destobject.txt. */
std::string CopyObjectName = "destdir/destobject.txt";
/* Initialize resources, such as network resources. */
InitializeSdk();
ClientConfiguration conf;
OssClient client(Endpoint, AccessKeyId, AccessKeySecret, conf);
CopyObjectRequest request(CopyBucketName, CopyObjectName);
request.setCopySource(SourceBucketName, SourceObjectName);
request.setVersionId("yourSourceObjectVersionId");
/* Copy the specified version of the source object. */
auto outcome = client.CopyObject(request);
if (outcome.isSuccess()) {
std::cout << "versionid:" << outcome.result().VersionId() << std::endl;
}
else {
/* Handle exceptions. */
std::cout << "CopyObject fail" <<
",code:" << outcome.error().Code() <<
",message:" << outcome.error().Message() <<
",requestId:" << outcome.error().RequestId() << std::endl;
return -1;
}
/* Release resources, such as network resources. */
ShutdownSdk();
return 0;
}
Use ossutil
For more information about how to restore a previous version of an object as the current version in a versioning-enabled bucket by using ossutil, see Copy objects.
Use RESTful APIs
If your business requires a high level of customization, you can directly call RESTful APIs. To directly call an API, you must include the signature calculation in your code. For more information, see CopyObject.