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.

Note OSS generates unique version IDs for objects uploaded by using PutObject, PostObject, CopyObject, and MultipartUpload.
In the following figure, when you use the PutObject operation to upload an object whose key is example.jpg, OSS generates a unique version ID of 111111 for the object.

When you use 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 of 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 use the PutObject operation to upload an object that has the same key again, OSS generates a new version with a unique version ID of 333333 for the object and stores the new version as the current version of the object. In the following figure, versions 111111 and 222222 are stored as previous versions.

Use the OSS console

  1. Log on to the OSS console.
  2. In the left-side navigation pane, click Buckets. On the Buckets page, click the name of the desired bucket.
  3. In the left-side navigation pane, click Files. On the page that appears, click Upload.
  4. In the Upload panel, configure the parameters described in the following table.
    1. Configure basic settings.
      Parameter Description
      Upload To Set the path in which an object is stored after the object is uploaded to the bucket.
      • Current: Objects are uploaded to the current directory.
      • Specified: Objects are uploaded to the specified directory. You must enter the directory name. If the directory whose name you entered does not exist, OSS automatically creates the directory and uploads the object to the directory.
        The directory name must meet the following conventions:
        • The name can contain only UTF-8 characters. The name must be 1 to 254 characters in length.
        • The name cannot start with a forward slash (/) or backslash (\).
        • The name cannot contain consecutive forward slashes (/).
        • The name of a directory cannot be two consecutive periods (..).
      File ACL Set the access control list (ACL) for the object.
      • Inherited from Bucket: The ACL of the objects is the same as that of the bucket.
      • Private: Only the object owner or authorized users can read and write the object that you want to upload. Other users cannot access the object without authorization. We recommend that you set the parameter to Private.
      • Public Read: Only the object owner or authorized users can perform write operation on the object that you want to upload. Other users, including anonymous users, can only read the object. This may result in unauthorized access to the object and high fees. Proceed with caution when you set this parameter to Public Read.
      • Public Read/Write: All users, including anonymous users, can access the object that you want to upload and write data to the object. This may result in unauthorized access to the object and high fees. If a user uploads prohibited data or information to your object, your legitimate interests and rights may be infringed. We recommend that you do not set this parameter to Public Read/Write except unless necessary.

      For more information, see Object ACL.

      Upload Acceleration After transfer acceleration is enabled for the bucket that contains the object, you can turn on Upload Acceleration if you want to accelerate the upload of the object.

      For more information, see Transfer acceleration.

      Files to Upload Select 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 to the Files to Upload section.

      If the directory that you select contains an unnecessary object, find the object and click Remove in the Actions column to remove the object.

      Notice
      • 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 latest version.
      • When you upload an object that has the same name as an existing object in OSS to an unversioned bucket, the existing object is overwritten.
    2. Optional:Configure advanced settings such as Storage Class and Encryption Method.
      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 less than once to twice a month on average. IA objects have a minimum storage duration of 30 days. You are charged for data retrieval when you access these objects.
      • Archive: Archive is suitable for objects that are infrequently accessed. Archive objects have a minimum storage duration of 60 days. Before you can access an object of the Archive storage class, you must restore the object. The restoration takes about one minute, and you are charged data retrieval fees during the restoration process.
      • 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 an object of the Cold Archive storage class, you must restore the object. The amount of time required to restore a Cold Archive object depends on the data size and the restore mode. You are charged for data retrieval when you restore a Cold Archive object.

      For more information, see Overview.

      Encryption Method Configure server-side encryption method for an 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 data keys to encrypt objects. In addition, OSS uses regularly rotated master keys to encrypt data keys.
      • KMS: The default customer master key (CMK) stored in Key Management Service (KMS) or the specified 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 the objects when the objects are downloaded.
        • CMK ID: The keys generated by a specified CMK are used to encrypt different objects and the specified CMK ID is recorded in the metadata of the encrypted object. Objects are decrypted when they are downloaded by users who are granted 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 descriptive information for the object. 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, user metadata headers must be prefixed with x-oss-meta- and assigned values. Example: x-oss-meta-location:hangzhou.
  5. Click Upload.

    You can view the upload progress of objects on the Task List tab.

Use OSS SDKs

The following code provides examples on how to perform simple upload for a versioning-enabled bucket by using OSS SDKs for common programming languages. For more information about how to perform simple upload 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;

// Security risks may arise if you use the AccessKey pair of an Alibaba Cloud account to log on to OSS because the account has permissions on all API operations. We recommend that you use your RAM user's credentials to call API operations or perform routine operations and maintenance. To create a RAM user, log on to the RAM console.
$accessKeyId = "<yourAccessKeyId>";
$accessKeySecret = "<yourAccessKeySecret>";
// The endpoint of the China (Hangzhou) region is used in this example. Specify the actual endpoint.
$endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
$bucket= "<yourBucketName>";
// Specify the complete name of the object excluding the bucket name. Example: example/test.txt.
$object = "<yourObjectName>";
$content = "hello world";

$ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);

try {
    // Upload the object to the versioned 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. 
# Set yourBucketName to the name of your bucket. 
bucket = oss2.Bucket(auth, 'https://oss-cn-hangzhou.aliyuncs.com', 'yourBucketName')

# Upload an 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 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() {
  // Creates an OSSClient instance.
  client, err := oss.New("<yourEndpoint>", "<yourAccessKeyId>", "<yourAccessKeySecret>")
  if err != nil {
    fmt.Println("Error:", err)
    os.Exit(-1)
  }

  // Obtains the bucket.
  bucket, err := client.Bucket("<yourBucketName>")
  if err != nil {
    fmt.Println("Error:", err)
    os.Exit(-1)
  }

  var retHeader http.Header
  // Uploads a string. The oss.GetResponseHeader method is used to obtain the returned header.
  err = bucket.PutObject("<yourObjectName>", strings.NewReader("yourObjectValue"), oss.GetResponseHeader(&retHeader))
  if err != nil {
    fmt.Println("Error:", err)
    os.Exit(-1)
  }
  // Prints 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 OSS account information.*/
    std::string AccessKeyId = "yourAccessKeyId";
    std::string AccessKeySecret = "yourAccessKeySecret";
    std::string Endpoint = "yourEndpoint";
    std::string BucketName = "yourBucketName";
    std::string ObjectName = "yourObjectName";

    /*Initialize 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;
        ShutdownSdk();
        return -1;
    }

    /*Release network resources.*/
    ShutdownSdk();
    return 0;
}

Use ossutil

For more information about how to perform simple upload for a versioning-enabled bucket by using ossutil, see Upload objects.

Use the RESTful API

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 the information about all object versions and delete markers in a versioning-enabled bucket.

  • 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 names 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, the 900 versions of the example.jpg object and 100 versions of the photo.jpg object are returned. Versions are returned in alphabetical order of object keys first and then in the order of time when the versions are generated.

In the following figure, all object versions including delete markers are returned when the GetBucketVersions (ListObjectVersions) operation is called. 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

  1. Log on to the OSS console.
  2. 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 restore 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 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. 
        String accessKeyId = "yourAccessKeyId";
        String accessKeySecret = "yourAccessKeySecret";
        // Specify the bucket name. Example: examplebucket. 
        String bucketName = "examplebucket";

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

        try {
            // List the versions of all objects and delete markers within 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 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. 
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 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 versioned bucket. 
# List the versions of all objects including delete markers in a 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)

    # View the version information about 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)

    # View the version information about 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:', version_info.is_latest)

    is_truncated = result.is_truncated

    # Check whether the versions of all objects are listed. If the versions of all objects are incompletely listed, the list operation continues. If the 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.
    // Set yourEndpoint to the endpoint of the region where the bucket is located. For example, if your bucket is in the China (Hangzhou) region, set yourEndpoint to https://oss-cn-hangzhou.aliyuncs.com.
    // Security risks may arise if you use the AccessKey pair of an Alibaba Cloud account to log on to OSS because the account has permissions on all API operations. We recommend that you use your RAM user's credentials to call API operations or perform routine operations and maintenance. 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 bucket name.
    bucketName := "examplebucket"
    bucket,err := client.Bucket(bucketName)
    if err != nil {
        HandleError(err)
    }

    // List the versions of all objects including delete markers within 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 information about the versions of returned objects.
        for _, dirName := range lor.ObjectVersions{
            fmt.Println("Versionid:",dirName.VersionId)
            fmt.Println("Key:",dirName.Key)
            fmt.Println("Is Latest",dirName.IsLatest)
        }
        // Display the version information of the listed delete markers.
         for _, marker  := range lor.ObjectDeleteMarkers {
            fmt.Println(marker.VersionId)
            fmt.Println(marker.Key)
        }
        // Check whether the versions of all objects and delete markers are listed. If the versions of only part of objects are listed, the list operation continues. If the versions of all objects are completely listed, the list operation ends.
        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 the RESTful API

If your program requires more custom options, you can call RESTful API operations. To directly call an API, you must include the signature calculation in your code. For more information, see GetBucketVersions(ListObjectVersions).

Download objects

You can download the current version or a specified version of an object from a versioning-enabled bucket.

By default, if a GetObject request in which no version ID is specified is sent to download an object, the current version of the object is returned. In the following figure, the current version of the object, whose version ID is 333333, is returned.

If a GetRequest in which the no version ID is specified is sent 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. In the following figure, a request in which a version ID is specified is sent to download the object whose version ID is 222222.

Use the OSS console

  1. Log on to the OSS console.
  2. In the left-side navigation pane, click Buckets. On the Buckets page, click the name of the desired bucket.
  3. In the left-side navigation pane, choose Files > Files.
  4. Click the version that you want to download. In the panel that appears, click Download on the right side of Object URL.

Use OSS SDKs

The following code provides examples on how to download objects in 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 the 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 Object Storage Service (OSS) because the account has permissions on all API operations. 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;

// Security risks may arise if you use the AccessKey pair of an Alibaba Cloud account to log on to OSS because the account has permissions on all API operations. We recommend that you use your RAM user's credentials to call API operations or perform routine operations and maintenance. To create a RAM user, log on to the RAM console.
$accessKeyId = "<yourAccessKeyId>";
$accessKeySecret = "<yourAccessKeySecret>";
// The endpoint of the China (Hangzhou) region is used in this example. Specify the actual endpoint.
$endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
$bucket= "<yourBucketName>";
// Specify the complete name of the object excluding the bucket name. Example: example/test.txt.
$object = "<yourObjectName>";
// Specify the version ID of the version you want to download.
$versionId = "<yourObjectVersionId>";

$ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);

try{
    // Download the version with the specified version ID.
    $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',
  // Set yourbucketname to the name of your bucket. 
  bucket: 'yourbucketname'
});

async function get() {
  const get = await client.get(name, {    
      // View 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. The full path cannot contain the bucket name. 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 where the object is stored, object name, object metadata, and an input stream. 
    var request = new GetObjectRequest(bucketName, objectName)
    {
        // Specify the version ID of the version you want to download. 
        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() {
  // Creates an OSSClient instance.
  client, err := oss.New("<yourEndpoint>", "<yourAccessKeyId>", "<yourAccessKeySecret>")
  if err != nil {
    fmt.Println("Error:", err)
    os.Exit(-1)
  }

  // Obtains the bucket.
  bucket, err := client.Bucket("<yourBucketName>")
  if err != nil {
    fmt.Println("Error:", err)
    os.Exit(-1)
  }

  var retHeader http.Header
  // Downloads the object with the version ID: yourObjectVersionId to the cache.
  _, err = bucket.GetObject("youObjectName", oss.VersionId("yourObjectVersionId"), oss.GetResponseHeader(&retHeader))
  if err != nil {
    fmt.Println("Error:", err)
    os.Exit(-1)
  }
  // Prints 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 OSS account information.*/
    std::string AccessKeyId = "yourAccessKeyId";
    std::string AccessKeySecret = "yourAccessKeySecret";
    std::string Endpoint = "yourEndpoint";
    std::string BucketName = "yourBucketName";
    std::string ObjectName = "yourObjectName";

    /*Initialize network resources.*/
    InitializeSdk();

    ClientConfiguration conf;
    OssClient client(Endpoint, AccessKeyId, AccessKeySecret, conf);

    /*Download an 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;
        /*View 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;
            ShutdownSdk();
            return -1;
    }

    /*Release 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 the RESTful API

If your program requires more custom options, you can call RESTful API operations. To directly call an API, you must include the signature calculation in your code. For more information, see GetObject.

Delete objects

You can specify an object version ID 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 an object version ID in the DeleteObject request, OSS adds a delete marker as the current version of the object.

Notice
  • 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.
  • We recommend that you do not enable the OSS-HDFS service and versioning for a bucket.

    If you enable versioning for a bucket for which the OSS-HDFS service is enabled, data that is overwritten or deleted is saved as previous versions. When you overwrite or delete data in the .dlsdata/ directory by using the methods that are supported by the OSS-HDFS service, a message that indicates that the data is successfully overwritten or deleted is displayed. OSS retains the data that is overwritten or deleted as previous versions because versioning is enabled for the bucket.

    In this case, you can specify version IDs to delete previous versions of objects from the .dlsdata/ directory.

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 examples describe how OSS deletes an object based on whether the version ID is 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 delete. The delete marker has a unique version ID but does not have data and ACL. In the following figure, a delete marker with the version ID of 444444 is added as the current version.
  • If the version ID is specified in the DeleteObject request, the specified version is permanently deleted. In the following figure, the version whose ID is 333333 is permanently deleted.

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.

Warning You cannot restore a previous version of an object after it is deleted. Proceed with caution.
  1. Log on to the OSS console.
  2. In the left-side navigation pane, click Buckets. On the Buckets page, click the name of the desired bucket.
  3. In the left-side navigation pane, choose Files > Files.
  4. 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 Batch Operation > Permanently Delete.

  5. 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 an object with specified version ID from a versioning-enabled bucket by using OSS SDKs for common programming languages. For more information about how to delete an object with specified version ID 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;

// Security risks may arise if you use the AccessKey pair of an Alibaba Cloud account to log on to OSS because the account has permissions on all API operations. We recommend that you use your RAM user's credentials to call API operations or perform routine operations and maintenance. To create a RAM user, log on to the RAM console.
$accessKeyId = "<yourAccessKeyId>";
$accessKeySecret = "<yourAccessKeySecret>";
// The endpoint of the China (Hangzhou) region is used in this example. Specify the actual endpoint.
$endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
$bucket= "<yourBucketName>";
// Specify the complete name of the object excluding the bucket name. 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. 
# Set yourBucketName to the name of the bucket. 
bucket = oss2.Bucket(auth, 'https://oss-cn-hangzhou.aliyuncs.com', 'yourBucketName')
# yourObjectName specifies the complete path of the object excluding the bucket name. 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 specified version ID or the object whose current version is a delete marker with the specified 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. The full path cannot contain the bucket name. Example: exampledir/exampleobject.txt. 
var objectName = "exampledir/exampleobject.txt";
// Specify the version ID of an object or a 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.
  client, err := oss.New("<yourEndpoint>", "<yourAccessKeyId>", "<yourAccessKeySecret>")
  if err != nil {
    fmt.Println("Error:", err)
    os.Exit(-1)
  }

  // Obtain 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 OSS account information. */
    std::string AccessKeyId = "yourAccessKeyId";
    std::string AccessKeySecret = "yourAccessKeySecret";
    std::string Endpoint = "yourEndpoint";
    std::string BucketName = "yourBucketName";
    std::string ObjectName = "yourObjectName";

    /* Initialize 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;
        ShutdownSdk();
        return -1;
    }

    /* Release 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 the RESTful API

If your program requires more custom options, you can call RESTful API operations. 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 preserved. You can restore a specified previous version of an object as the current version.

You can restore a previous version of an object as the current version by using one of the following methods:
  • Use CopyObject to copy the previous version to the same bucket

    The copied previous version becomes the current version of the object and all versions of the object are preserved.

    In the following figure, a previous version whose ID is 222222 is copied to the same bucket. OSS adds the copied version as a new version whose ID is 444444. The new 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 a previous version and version 444444 is the current version.
  • Permanently delete the current version of the object

    In the following figure, the current version whose ID is 222222 is permanently deleted by using a DeleteObject request in which the version ID is specified. The most recent previous version whose ID is 111111 becomes the current version of the object.

Notice We recommend that you use CopyObject to restore a previous version as the current version because the current version cannot be restored after it is permanently deleted.

Use the OSS console

  1. Log on to the OSS console.
  2. In the left-side navigation pane, click Buckets. On the Buckets page, click the name of the desired bucket.
  3. In the left-side navigation pane, choose Files > Files.
  4. Restore a specified previous version of an object as the current version.
    Notice 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 then choose Batch Operation > Restore.

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.

If your program requires more custom options, you can call RESTful API operations. To directly call an API, you must include the signature calculation in your code. For more information, see CopyObject.