Manage versioned objects

更新时间:
复制 MD 格式

When you enable versioning for a bucket, OSS assigns a unique ID to each object version. Existing objects retain their content and ACL. Versioning prevents accidental overwrites or deletions and lets you query or restore previous versions.

Usage notes

When you upload, list, download, delete, or restore objects in a versioning-enabled bucket:

  • OSS maintains a current version and zero or more previous versions for each object.

  • Objects that exist in a bucket before you enable versioning have a version ID of null.

  • For clarity, the version IDs in the figures in this topic are simplified.

  • A lifecycle rule that transitions an object to a different storage class does not create a new version.

Versioning.

Upload objects

When you upload an object to a versioning-enabled bucket, OSS assigns a unique version ID to it.

Note

PutObject, PostObject, CopyObject, and MultipartUpload each assign a unique version ID to the newly created object.

When you PUT an object, OSS assigns it a unique version ID (for example, 111111).

When you PUT an object with the same name (key=example.jpg), the existing version (ID=111111) becomes a previous version and the new version (ID=222222) becomes current. Uploading the same key again makes ID=111111 and ID=222222 previous versions while ID=333333 becomes current.

Use the OSS console

  1. Log on to the OSS console.

  2. In the left-side navigation pane, click Buckets. On the Buckets page, find and click the desired bucket.

  3. In the left-side navigation tree, choose Object Management > Objects.

  4. On the Objects page, click Upload Object.

  5. In the Upload Object panel, configure the following parameters.

    1. Configure basic options.

      Parameter

      Description

      Upload To

      Specify the storage path for the object.

      • Current Directory: Upload the object to the current directory.

      • Specified Directory: Upload the object to a specified directory. You must enter a directory name. If the directory does not exist, OSS automatically creates the directory and uploads the object to it.

        The directory name must meet the following requirements:

        • The name must be 1 to 254 characters in length and must be UTF-8 encoded.

        • The name cannot start with a forward slash (/) or a backslash (\).

        • The name cannot contain consecutive forward slashes (/).

        • The name cannot be two consecutive periods (..).

      Object ACL

      Set the access control list (ACL) for the object.

      • Inherited from Bucket: The object inherits the ACL of the bucket.

      • Private (Recommended): Only the object owner has read and write permissions on the object. Other users cannot access the object.

      • Public Read: The object owner has read and write permissions on the object. Other users, including anonymous users, have only read permissions on the object. This may result in data leaks and unexpectedly high fees. Proceed with caution.

      • Public Read/Write: All users, including anonymous users, can read from and write to the object. This setting poses a significant security risk, as malicious users could write unauthorized content to your object. Avoid granting public read/write permissions unless absolutely necessary.

      Object ACL.

      Files to Upload

      Select the files or folders that you want to upload.

      Click Select Files or Select Folders to select local files or folders. You can also drag the files or folders to the Files to Upload area.

      If a selected folder contains files that you do not want to upload, find the files in the list and click Remove in the Actions column.

      Important
      • If you upload an object to a bucket for which versioning is disabled and the object has the same name as an existing object, the existing object is overwritten.

      • If you upload an object to a bucket for which versioning is enabled and the object has the same name as an existing object, the new object becomes the current version and the existing object becomes a previous version.

    2. Optional: Click the image.png icon to the right of Advanced Settings to configure advanced options such as Storage Class and Server-side Encryption.

      Parameter

      Description

      Storage Class

      Set the storage class of the object. Valid values:

      • Inherited from Bucket (Default): The object inherits the storage class of the bucket.

      • Standard: Provides reliable, highly available, and high-performance object storage for frequently accessed data. This storage class is suitable for various scenarios, such as social and sharing image applications, audio and video applications, large websites, and big data analytics. The Standard storage class supports zone-redundant storage (ZRS) and locally redundant storage (LRS).

      • IA: Provides a highly durable object storage service at a lower storage cost. This storage class has a minimum billable size of 64 KB and a minimum storage period of 30 days. Data can be accessed in real time, but data retrieval fees apply. This storage class is suitable for scenarios with a low access frequency, for example, once or twice a month on average. The IA storage class supports zone-redundant storage and locally redundant storage.

      • Archive: Provides a highly durable object storage service at an extremely low storage cost. This storage class has a minimum billable size of 64 KB and a minimum storage period of 60 days. You can access Archive objects either by restoring them first (which takes about one minute) or by accessing them directly. Fees apply for both restoration and direct reads. This storage class is suitable for long-term data archival scenarios, such as archival data, medical images, scientific materials, and video footage. The Archive storage class supports zone-redundant storage and locally redundant storage.

      • Cold Archive: Provides a highly durable object storage service at a lower storage cost than Archive. This storage class has a minimum billable size of 64 KB and a minimum storage period of 180 days. Cold Archive objects must be restored before you can access them. The restoration time depends on the object size and the restoration mode. Data retrieval fees and request fees are incurred for restoration. This storage class is suitable for storing cold data for an extended period, such as data that requires long-term retention for compliance purposes, raw data accumulated in the big data and AI fields, long-term media assets in the film and television industries, and archived videos in the online education industry. The Cold Archive storage class supports only locally redundant storage.

      • Deep Cold Archive: Provides a highly durable object storage service at a lower storage cost than Cold Archive. This storage class has a minimum billable size of 64 KB and a minimum storage period of 180 days. Deep Cold Archive objects must be restored before you can access them. The restoration time depends on the object size and the restoration mode. Data retrieval fees and request fees are incurred for restoration. This storage class is suitable for storing extremely cold data for an extended period, such as raw data accumulated in the big data and AI fields, long-term media assets, regulatory and compliance archives, and tape replacement. The Deep Cold Archive storage class supports only locally redundant storage.

      Storage classes.

      Encryption Method

      Set the server-side encryption method for the object. Valid values:

      • Inherited from Bucket (Default): The object inherits the server-side encryption method of the bucket.

      • OSS-Managed: OSS encrypts each object with a unique, OSS-managed key. For added protection, these keys are themselves encrypted with a master key.

      • KMS: Use the default customer master key (CMK) managed by KMS or a specified CMK for encryption and decryption.

        To use KMS encryption, activate KMS first. Purchase a Dedicated KMS instance.

        The following describes the CMK parameter:

        The encryption key is in the <alias>(CMK ID) format, where <alias> is the alias of the CMK and CMK ID is the ID of the CMK. Valid values:

        • alias/acs/oss(CMK ID): The default KMS-managed CMK is used to generate different keys to encrypt different objects. The objects are automatically decrypted when they are downloaded.

        • alias/<cmkname>(CMK ID): This option uses a specified CMK to generate a unique encryption key for each object. The object's metadata stores the CMK ID. When a user with the required permissions downloads the object, OSS automatically decrypts it. <cmkname> is the optional alias of the CMK that you specified when you created the CMK.

          Before you use a specified CMK ID, create a regular key or an external key in the same region as the bucket in the KMS console. For more information, see Create a CMK.

      • Encryption Algorithm: You can select AES256 or SM4.

      User-defined Metadata

      Add descriptive information to the object. You can add multiple user-defined metadata entries. The total size of all user-defined metadata cannot exceed 8 KB. Each user-defined metadata key must be prefixed with x-oss-meta- and assigned a value. Example: x-oss-meta-location:hangzhou.

    3. Click Upload Object.

      You can view the upload progress of each file on the Upload Tasks tab of the Task List panel.

Use Alibaba Cloud SDKs

The following code uploads an object to a versioning-enabled bucket. For other SDKs, see SDK overview.

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.*;
import java.io.ByteArrayInputStream;

public class Demo {
    public static void main(String[] args) throws Exception {
        // This example uses the endpoint of the China (Hangzhou) region. Specify the actual endpoint.
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the bucket name, for example, examplebucket.
        String bucketName = "examplebucket";
        // Specify the full path of the object. The full path cannot include the bucket name.
        String objectName = "exampledir/object";
        // Specify the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou.
        String region = "cn-hangzhou";

        // Create an OSSClient instance.
        // When the OSSClient instance is no longer needed, call the shutdown method to release resources.
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            // This example shows how to upload a string.
            String content = "Hello OSS";
            PutObjectResult result = ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(content.getBytes()));
            // View the VersionId of the uploaded 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();
            }
        }
    }
}
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',
  // Obtain access credentials from environment variables. Before you run the sample code, make sure that you have configured environment variables OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET. 
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
  authorizationV4: true,
  // Specify the name of the bucket. 
  bucket: 'yourbucketname'
});

async function put() {
  const result = await client.put('fileName', path.normalize('D:\\localpath\\examplefile.txt'));
  console.log(result.res.headers['x-oss-version-id']); // Display the version ID of the uploaded object. 
}
put();
using System.Text;
using Aliyun.OSS;
using Aliyun.OSS.Common;

// Set yourEndpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
var endpoint = "yourEndpoint";
// Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Set bucketName to the name of the bucket, for example, examplebucket.
var bucketName = "examplebucket";
// Set objectName to the full path of the object. The full path cannot include the bucket name. For example, exampledir/exampleobject.txt.
var objectName = "exampleobject.txt";
var objectContent = "More than just cloud.";
// Set region to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set region to cn-hangzhou.
const string region = "cn-hangzhou";

// Create a ClientConfiguration instance and modify the default parameters as needed.
var conf = new ClientConfiguration();

// Use Signature Version 4.
conf.SignatureVersion = SignatureVersion.V4;

// Create an OssClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);
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);
}
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;

int main(void)
{
    /* Initialize the OSS account information. */
            
    /* Set yourEndpoint to the Endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
    std::string Endpoint = "yourEndpoint";
    /* Set yourRegion to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. */
    std::string Region = "yourRegion";
    /* Specify the bucket name. Example: examplebucket. */
    std::string BucketName = "examplebucket";
    /* Specify the full path of the Object. The full path cannot contain the bucket name. Example: exampledir/exampleobject.txt. */
    std::string ObjectName = "exampledir/exampleobject.txt";

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

    ClientConfiguration conf;
    conf.signatureVersion = SignatureVersionType::V4;
    /* Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);
    client.SetRegion(Region);
    std::shared_ptr<std::iostream> content = std::make_shared<std::stringstream>();
    *content << "test cpp sdk";
    PutObjectRequest request(BucketName, ObjectName, content);

    /* Upload the file. */
    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 network resources. */
    ShutdownSdk();
    return 0;
}
package main

import (
	"context"
	"flag"
	"log"
	"strings"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Specify the global variables.
var (
	region     string // The region in which the bucket is located.
	bucketName string // The name of the bucket.
	objectName string // The name of the object.
)

// Define the init function used to initialize parameters.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
	flag.StringVar(&objectName, "object", "", "The name of the object.")
}

func main() {
	// Parse command line parameters.
	flag.Parse()

	// Check whether the bucket name is empty.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is empty.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Check whether the object name is empty.
	if len(objectName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, object name required")
	}

	// Specify the content that you want to upload.
	content := "hi oss"

	// Load the default configurations and specify the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSS client.
	client := oss.NewClient(cfg)

	// Create a request to upload an object.
	request := &oss.PutObjectRequest{
		Bucket: oss.Ptr(bucketName),        // The name of the bucket.
		Key: oss.Ptr(objectName),        // The name of the object.
		Body:   strings.NewReader(content), // The content that you want to upload.
	}

	// Execute the request to upload an object.
	result, err := client.PutObject(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to put object %v", err)
	}

	// Display the version ID of the object.
	log.Printf("put object result versionId:%#v\n", *result.VersionId)
}
import argparse
import requests
import alibabacloud_oss_v2 as oss

# Create a command line argument parser.
parser = argparse.ArgumentParser(description="put object sample")
# Configure the --region command line argument to specify the region where the bucket is located. This argument is required.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# Configure the --bucket command line argument to specify the name of the bucket. This argument is required.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
# Configure the --endpoint command line argument to specify the endpoint that other services can use to access OSS. This argument is optional.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
# Configure the --key command line argument to specify the name of the object. This argument is required.
parser.add_argument('--key', help='The name of the object.', required=True)

def main():
    args = parser.parse_args()  # Parse the command line arguments.

    # Obtain access credentials from environment variables for authentication.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Obtain the default configurations of the SDK and specify the credential provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider
    # Specify the region in which the bucket is located.
    cfg.region = args.region
    # If the endpoint parameter is provided, specify the endpoint.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Use the configurations to create an OSSClient instance.
    client = oss.Client(cfg)

    # Upload a local file.
    local_file_path = '/yourLocalFilePath/yourFileName'
    with open(local_file_path, 'rb') as file:
        data = file.read()

    # Execute the request to upload an object, and specify the bucket name, object name, and data content.
    result = client.put_object(oss.PutObjectRequest(
        bucket=args.bucket,
        key=args.key,
        body=data,
    ))

    # Display the HTTP status code in the response, the request ID, and the MD5 hash, ETag, CRC-64 value, and version ID of the object to check whether the request is successful.
    print(f'status code: {result.status_code},'
          f' request id: {result.request_id},'
          f' content md5: {result.content_md5},'
          f' etag: {result.etag},'
          f' hash crc64: {result.hash_crc64},'
          f' version id: {result.version_id},'
    )

if __name__ == "__main__":
    main()  # The entry point of the script. Call the main() function when the script is directly run.
<?php

// Include the autoload file to load dependencies.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Describe command-line parameters.
$optsdesc = [
    "region" => ['help' => 'The region in which the bucket is located', 'required' => True], // (Required) Specify the region in which the bucket is located.
    "endpoint" => ['help' => 'The domain names that other services can use to access OSS', 'required' => False], // (Optional) Specify the OSS endpoint.
    "bucket" => ['help' => 'The name of the bucket', 'required' => True], // (Required) Specify the name of the bucket.
    "key" => ['help' => 'The name of the object', 'required' => True], // (Required) Specify the name of the object.
];

// Generate a list of long options to parse the command-line parameters.
$longopts = \array_map(function ($key) {
    return "$key:"; // Add a colon (:) to the end of each parameter to indicate that a value is required.
}, array_keys($optsdesc));

// Parse the command-line parameters.
$options = getopt("", $longopts);

// Check whether the required parameters are missing.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help'];
        echo "Error: the following arguments are required: --$key, $help"; // Display the required but missing parameters.
        exit(1);
    }
}

// Obtain the values of the command-line parameters and assign the values to variables.
$region = $options["region"]; // The region in which the bucket is located.
$bucket = $options["bucket"]; // The name of the bucket.
$key = $options["key"]; // The name of the object.

// Load the AccessKey ID and AccessKey secret from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Use the default configuration of the SDK.
$cfg = Oss\Config::loadDefault();

// Specify the credential provider.
$cfg->setCredentialsProvider($credentialsProvider);

// Specify the region.
$cfg->setRegion($region);

// If an endpoint is provided, specify the endpoint.
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]);
}

// Create an OSSClient instance.
$client = new Oss\Client($cfg);

// Specify the data that you want to upload.
$data = 'Hello OSS';

// Create a simple upload request.
$request = new Oss\Models\PutObjectRequest(
                bucket: $bucket,
                key: $key,
            );

// Set the request body to the data stream.
$request->body = Oss\Utils::streamFor($data);

// Use the putObject method to upload the data.
$result = $client->putObject($request);

// Display the returned result.
printf(
    'status code:' . $result->statusCode . PHP_EOL . // The HTTP status code.
    'request id:' . $result->requestId . PHP_EOL . // The request ID.
    'etag:' . $result->etag . PHP_EOL // The ETag of the object.
);

Use ossutil

To upload objects to a versioning-enabled bucket by using ossutil, see cp (upload objects).

Use a REST API

You can also call the REST API directly. PutObject.

List objects

In a versioning-enabled bucket, call GetBucketVersions (ListObjectVersions) to retrieve information about all object versions, including delete markers.

  • The GetBucket (ListObject) operation returns only current object versions that are not delete markers.

  • A single GetBucketVersions (ListObjectVersions) request returns up to 1,000 object versions. To retrieve all versions, send multiple requests.

    For example, if a bucket contains two keys, example.jpg and photo.jpg, where example.jpg has 900 versions and photo.jpg has 500 versions, a single request lists all 900 versions of example.jpg and the first 100 versions of photo.jpg. The results are sorted by key in lexicographical order, and then by version.

As the following figure shows, GetBucketVersions (ListObjectVersions) returns all versions including delete markers. GetBucket (ListObject) returns only current versions that are not delete markers, so only the object with version ID 444444 is returned.

OSS console

  1. Log on to the OSS console.

  2. Click Buckets, and then click the name of the target bucket.

    This page displays a paginated list of the current version of each object. To view all versions, including delete markers, go to the Objects page and click Show next to Previous Versions.

OSS SDK

The following code lists objects in a versioning-enabled bucket. For other SDKs, see SDK introduction.

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
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";
        // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the name of the bucket. Example: examplebucket. 
        String bucketName = "examplebucket";
        // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
        String region = "cn-hangzhou";

        // Create an OSSClient instance.
        // Call the shutdown method to release resources when the OSSClient is no longer in use. 
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        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();
            }
        }
    }
}
const OSS = require("ali-oss");

const client = new OSS({
  // Set region to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set region to oss-cn-hangzhou.
  region: 'yourregion',
  // Obtain access credentials from environment variables. Before running this sample code, make sure the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
  authorizationV4: true,
  // Specify the bucket name.
  bucket: 'yourbucketname'
});

// List the version information of all objects, including delete markers.
async function getObjectVersions() {
  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);
}

getObjectVersions();
import argparse
import alibabacloud_oss_v2 as oss

# Create a command-line argument parser and describe the purpose of the script.
parser = argparse.ArgumentParser(description="list object versions sample")

# Specify the --region parameter to indicate the region in which the bucket is located. This parameter is required.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# Specify the --bucket parameter to indicate the name of the bucket. This parameter is required.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
# Specify the --endpoint parameter to indicate the endpoint of the region in which the bucket is located. This parameter is optional.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')

def main():
    # Parse the command-line arguments to obtain the specified values.
    args = parser.parse_args()

    # From the environment variables, load the authentication information required to access OSS.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Use the default configuration to create a cfg object and specify the credential provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider
    cfg.region = args.region

    # If a custom endpoint is provided, update the endpoint attribute of the cfg object with the provided endpoint.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Use the preceding settings to initialize the OSSClient instance.
    client = oss.Client(cfg)

    # Create a Paginator object that is used to list object versions by page.
    paginator = client.list_object_versions_paginator()

    # Iterate over pages.
    for page in paginator.iter_page(oss.ListObjectVersionsRequest(
            bucket=args.bucket,  # The bucket name.
        )
    ):
        # Iterate over object versions on the current page.
        for o in page.version:
            # Print the following information about each object version:
            # - key: the object key.
            # - size: the object size (bytes).
            # - version_id: the version ID.
            # - last_modified: the last modified time.
            print(f'Object version: {o.key}, Size: {o.size}, Version_id: {o.version_id}, Last_modified: {o.last_modified}')


# Call the main function to start the processing logic when the script is directly run.
if __name__ == "__main__":
    main()  # Specify the entry point of the script. The control flow starts here.

ossutil

To list objects in a versioning-enabled bucket by using ossutil, see ls (List resources at the account level).

RESTful API

You can also call the REST API directly. ListObjectVersions (GetBucketVersions).

Download objects

You can download the current version or a specific version of an object.

A GET request without a version ID returns the current version (ID=333333).

If the current version is a delete marker, the GET request returns 404 Not Found.

A GET request with a version ID returns that specific version (ID=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, find and click the desired bucket.

  3. In the left-side navigation tree, choose Object Management > Objects.

  4. On the Objects page, click Show to the right of Previous Versions.

  5. Click the object version that you want to download. In the panel that appears, click Download to the right of Object URL.

Use an OSS SDK

The following code downloads an object from a versioning-enabled bucket. For other SDKs, see SDK overview.

const OSS = require('ali-oss');

const client = new OSS({
  // Set yourregion to the region where the bucket is located. For example, for the China (Hangzhou) region, set Region to oss-cn-hangzhou.
  region: 'yourregion',
  // Obtain access credentials from environment variables. Before you run this code, ensure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
  authorizationV4: true,
  // Set yourbucketname to the name of the bucket.
  bucket: 'yourbucketname'
});

async function get() {
  // The name of the file.
  const result = await client.get('filename', {    
      // The version ID of the file to download.
      versionId: 'versionid',
  });
  console.log(result.content);
}
get();
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;

int main(void)
{
    /* Initialize the OSS account information. */
            
    /* Set yourEndpoint to the Endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
    std::string Endpoint = "yourEndpoint";
    /* Set yourRegion to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the Region to cn-hangzhou. */
    std::string Region = "yourRegion";
    /* Specify the bucket name, such as examplebucket. */
    std::string BucketName = "examplebucket";
    /* Specify the full path of the object. The full path cannot contain the bucket name, such as exampledir/exampleobject.txt. */
    std::string ObjectName = "exampledir/exampleobject.txt";

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

    ClientConfiguration conf;
    conf.signatureVersion = SignatureVersionType::V4;
    /* Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);
    client.SetRegion(Region);

    /* Download the file to the 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 the exception. */
            std::cout << "getObjectToBuffer fail" <<
        ",code:" << outcome.error().Code() <<
        ",message:" << outcome.error().Message() <<
        ",requestId:" << outcome.error().RequestId() << std::endl;
        return -1;
    }

    /* Release network resources. */
    ShutdownSdk();
    return 0;
}
import argparse
import alibabacloud_oss_v2 as oss

# Create a command line parameter parser
parser = argparse.ArgumentParser(description="get object sample")

# Specify the --region parameter to indicate the region in which the bucket is located. This parameter is required.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# Specify the --bucket parameter, which specifies the name of the bucket. This command line parameter is required.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
# Specify the --endpoint parameter to indicate the endpoint of the region in which the bucket is located. This parameter is optional.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
# Specify the --key parameter, which specifies the name of the object. This command line parameter is required.
parser.add_argument('--key', help='The name of the object.', required=True)
# Specify the --version_id parameter, which specifies the version ID of the source object. This command line parameter is required.
parser.add_argument('--version_id', help='The version ID of the object.', required=True)

def main():
    # Parse the command line parameters.
    args = parser.parse_args()

    # Obtain access credentials from environment variables for authentication.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Load the default configurations of the SDK and specify the credential provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider

    # Specify the region in which the bucket is located.
    cfg.region = args.region

    # If the endpoint parameter is provided, specify the endpoint.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Use the configurations to create an OSSClient instance.
    client = oss.Client(cfg)

    # Execute the request to download the object, and specify the bucket name and object name.
    result = client.get_object(oss.GetObjectRequest(
        bucket=args.bucket,  # Specify the name of the bucket.
        key=args.key,  # Specify the name of the object.
        version_id=args.version_id, # Specify the version ID.
    ))

    # Display the response to check whether the request is successful.
    print(f'status code: {result.status_code},'
          f' request id: {result.request_id},'
          f' content length: {result.content_length},'
          f' content range: {result.content_range},'
          f' content type: {result.content_type},'
          f' etag: {result.etag},'
          f' last modified: {result.last_modified},'
          f' content md5: {result.content_md5},'
          f' cache control: {result.cache_control},'
          f' content disposition: {result.content_disposition},'
          f' content encoding: {result.content_encoding},'
          f' expires: {result.expires},'
          f' hash crc64: {result.hash_crc64},'
          f' storage class: {result.storage_class},'
          f' object type: {result.object_type},'
          f' version id: {result.version_id},'
          f' tagging count: {result.tagging_count},'
          f' server side encryption: {result.server_side_encryption},'
          f' server side data encryption: {result.server_side_data_encryption},'
          f' next append position: {result.next_append_position},'
          f' expiration: {result.expiration},'
          f' restore: {result.restore},'
          f' process status: {result.process_status},'
          f' delete marker: {result.delete_marker},'
    )

    # Read the content of the object.
    content = result.body.read()

    # Save the content to a local file. In this example, the local file is named test.txt.
    with open('./test.txt', 'wb') as f:
        f.write(content)

    print(f'File saved to test.txt successfully!')

# Call the main function when the script is directly run.
if __name__ == "__main__":
    main()  # Specify the entry points in the main function of the script when the script is directly run.
package main

import (
	"context"
	"flag"
	"io"
	"log"
	"os"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Define global variables.
var (
	region     string // The region in which your bucket is located.
	bucketName string // The name of the bucket.
	objectName string // The name of the object.
)

// Specify the init function used to initialize command line parameters.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
	flag.StringVar(&objectName, "object", "", "The name of the object.")
}

func main() {
	// Parse command line parameters.
	flag.Parse()

	// Check whether the name of the bucket is specified.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is specified.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Check whether the name of the object is specified.
	if len(objectName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, object name required")
	}

	// Specify the path of the output file.
	outputFile := "downloaded.file" // Replace this parameter with the path in which you want to save the file.

	// Load the default configurations and specify the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSS client.
	client := oss.NewClient(cfg)

	// Create a query request.
	request := &oss.GetObjectRequest{
		Bucket:    oss.Ptr(bucketName),      // The name of the bucket
		Key:       oss.Ptr(objectName),      // The name of the object
		VersionId: oss.Ptr("yourVersionId"), // The version ID of the object
	}

	// Perform the query operation and process the result.
	result, err := client.GetObject(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to get object %v", err)
	}
	defer result.Body.Close() // Make sure that the response body is closed when the function is complete.

	// Read the entire file.
	data, err := io.ReadAll(result.Body)
	if err != nil {
		log.Fatalf("failed to read object %v", err)
	}

	// Write the content to the file.
	err = os.WriteFile(outputFile, data, 0644)
	if err != nil {
		log.Fatalf("failed to write to output file %v", err)
	}

	log.Printf("file downloaded successfully to %s", outputFile)
}
<?php

// Introduce autoload files to load dependency libraries.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Specify descriptions for command line arguments.
$optsdesc = [
    "region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // (Required) Specify the region in which the bucket is located.
    "endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // (Optional) Specify the endpoint that can be used by other services for accessing OSS.
    "bucket" => ['help' => 'The name of the bucket', 'required' => True], // (Required) Specify the name of the bucket.
    "key" => ['help' => 'The name of the object', 'required' => True], // (Required) Specify the name of the object.
];

// Convert the descriptions to a list of long options required by getopt.
// Add a colon (:) to the end of each parameter to indicate that a value is required.
$longopts = \array_map(function ($key) {
    return "$key:";
}, array_keys($optsdesc));

// Parse the command line arguments.
$options = getopt("", $longopts);

// Check whether the required parameters are configured.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help']; // Obtain help information for the parameters.
        echo "Error: the following arguments are required: --$key, $help" . PHP_EOL;
        exit(1); // Exit the program if the required parameters are not configured.
    }
}

// Obtain values from the parsed parameters.
$region = $options["region"]; // The region in which the bucket is located.
$bucket = $options["bucket"]; // The name of the bucket.
$key = $options["key"]; // The name of object.

// Load access credentials from environment variables.
// Use EnvironmentVariableCredentialsProvider to retrieve the AccessKey ID and AccessKey secret from environment variables.    
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Use the default configuration of the SDK.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider); // Specify the credential provider.
$cfg->setRegion($region); // Specify the region in which the bucket is located.
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]); // Specify the endpoint if one is provided.
}

// Create an OSSClient instance.
$client = new Oss\Client($cfg);

// Create a GetObjectRequest object to obtain the content of the specified object.
$request = new Oss\Models\GetObjectRequest(
                bucket: $bucket,
                key: $key,
                versionId:"yourVersionId",// Specify the version ID of the object.
);

// Query the object.
$result = $client->getObject($request);

// Specify the local path to save the object.
$localFilePath = './test/file.txt'; // Replace this parameter with the actual local file path.

// Write the content to the local file.
file_put_contents($localFilePath, $result->body->getContents());

// Display the result.
// Output the HTTP status code, request ID, and content of the object.
printf(
    'status code:' . $result->statusCode . PHP_EOL . // The HTTP status code. For example, HTTP status code 200 indicates that the request succeeded.
    'request id:' . $result-> requestId. PHP_EOL // The request ID, which is used to debug or trace a request.
);

Use ossutil

To download objects from a versioning-enabled bucket by using ossutil, see cp (download objects).

Use a REST API

You can also call the REST API directly. GetObject.

Delete objects

In a versioning-enabled bucket, you can permanently delete an object by specifying its version ID or by configuring a lifecycle rule. If you delete without specifying a version ID, OSS inserts a delete marker as the current version.

Important
  • After you enable versioning, deleting an object without specifying a version ID does not delete its current or noncurrent versions by default.

  • Do not enable the OSS-HDFS service and versioning on the same bucket. This can lead to service instability. To ensure stable operation, suspend versioning as soon as possible and configure a lifecycle rule to clean up delete markers.

    How do I handle a bucket for which both OSS-HDFS and versioning are enabled?.

  • Expiration: Applies to the current version of an object. When the current version of an object expires, OSS creates a delete marker, and the expired version becomes a noncurrent version.

  • NoncurrentVersionExpiration: Applies to noncurrent versions of an object. This action permanently deletes these versions.

To use versioning with lifecycle rules, see Lifecycle configuration elements.

The following describes DELETE behavior with and without a specified version ID.

  • If you do not specify a version ID, OSS inserts a delete marker as the current version. The delete marker has a unique version ID but no data or ACL. In the following figure, the current version is a delete marker with version ID 444444.

  • If you specify a version ID, OSS permanently deletes that version. In the following figure, the version with ID 333333 is deleted.

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

Noncurrent versions of objects cannot be restored after they are permanently deleted. Proceed with caution.

  1. Log on to the OSS console.

  2. In the left-side navigation pane, click Buckets. On the Buckets page, find and click the desired bucket.

  3. In the left-side navigation tree, choose Object Management > Objects.

  4. On the Objects page, click Show next to Previous Versions.

  5. Find the unneeded noncurrent versions and do one of the following:

    • To delete a delete marker, click Permanently Delete in the Actions column.

    • To delete an object version, move the pointer over the image.png icon in the Actions column and click Permanently Delete.

    You can also select multiple noncurrent versions and click Permanently Delete at the bottom of the page.

  6. Click OK.

    You can also configure a lifecycle rule to periodically delete noncurrent versions. Overview of lifecycle rules.

OSS SDK

The following code deletes a specific version from a versioning-enabled bucket. For other SDKs, see SDK overview.

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;

public class Demo {
    public static void main(String[] args) throws Exception {
        // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the name of the bucket. Example: examplebucket. 
        String bucketName = "examplebucket";
        // Specify the full path of the object. Do not include the bucket name in the full path. 
        String objectName = "exampledir/object";
        String versionId  = "CAEQMxiBgICAof2D0BYiIDJhMGE3N2M1YTI1NDQzOGY5NTkyNTI3MGYyMzJm****";
        // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
        String region = "cn-hangzhou";

        // Create an OSSClient instance. 
        // Call the shutdown method to release resources when the OSSClient is no longer in use.
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            // Delete the specified version of the object. 
            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();
            }
        }
    }
}
const OSS = require("ali-oss");

const client = new OSS({
  // Replace yourregion with the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set Region to oss-cn-hangzhou.
  region: 'yourregion',
  // Obtain access credentials from environment variables. Before running this sample code, make sure the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
  authorizationV4: true,
  // Replace yourbucketname with the bucket name.
  bucket: 'yourbucketname'
});

// Specify the versionId of the object.
const versionId = "versionId";
// Specify the object.
const objectName = "exampleobject.txt";
async function deleteVersionObject() {
  const result = await client.delete(objectName, {
    versionId,
  });
  console.log(result);
}

deleteVersionObject();
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";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// 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";
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
const string region = "cn-hangzhou";

// Create a ClientConfiguration instance and modify the default parameters based on your requirements.
var conf = new ClientConfiguration();

// Use the signature algorithm V4.
conf.SignatureVersion = SignatureVersion.V4;

// Create an OSSClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);
try
{
    // Specify the version ID of the object or the delete marker that you want to delete. 
    var request = new DeleteObjectRequest(bucketName, objectName)
    {
        VersionId = versionid
    };
    client.DeleteObject(request);
    Console.WriteLine("Delete object succeeded");
}
catch (Exception ex)
{
    Console.WriteLine("Delete object failed. {0}", ex.Message);
}
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;

int main(void)
{
    /* Initialize the OSS account information. */
            
    /* Set yourEndpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
    std::string Endpoint = "yourEndpoint";
    /* Set yourRegion to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. */
    std::string Region = "yourRegion";
    /* Specify the bucket name, for example, examplebucket. */
    std::string BucketName = "examplebucket";
    /* Specify the full path of the object. The full path cannot contain the bucket name. For example, exampledir/exampleobject.txt. */
    std::string ObjectName = "exampledir/exampleobject.txt";

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

    ClientConfiguration conf;
    conf.signatureVersion = SignatureVersionType::V4;
    /* Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);
    client.SetRegion(Region);

    /* Delete the object with the specified versionId or the object associated with the delete marker that has the specified versionId. */
    auto outcome = client.DeleteObject(DeleteObjectRequest(BucketName, ObjectName, "yourObjectVersionIdOrDeleteMarkerVersionId"));
    /* If the versionId of an object is specified, the returned delete_marker is None and the returned versionId is the versionId of the specified object. */
    /* If the versionId of a delete marker is specified, the returned delete_marker is True and the returned versionId is the versionId of the specified delete marker. */
    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 network resources. */
    ShutdownSdk();
    return 0;
}
package main

import (
	"context"
	"flag"
	"log"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Define global variables.
var (
	region     string // The region where the bucket is located.
	bucketName string // The name of the bucket.
	objectName string // The name of the object.
)

// init is used to initialize command-line flags.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
	flag.StringVar(&objectName, "object", "", "The name of the object.")
}

func main() {
	// Parse command-line flags.
	flag.Parse()

	// Check if the bucket name is provided.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check if the region is provided.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Check if the object name is provided.
	if len(objectName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, object name required")
	}

	// Load the default configuration and set the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSS client.
	client := oss.NewClient(cfg)

	// Create a request to delete the object.
	request := &oss.DeleteObjectRequest{
		Bucket:    oss.Ptr(bucketName),      // The name of the bucket.
		Key:       oss.Ptr(objectName),      // The name of the object.
		VersionId: oss.Ptr("yourVersionId"), // Replace with the actual versionId of the object.
	}

	// Execute the delete operation and handle the result.
	result, err := client.DeleteObject(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to delete object %v", err)
	}

	// Print the result.
	log.Printf("delete object result:%#v\n", result)
}
<?php

// Import the autoloader file to ensure that dependency libraries are loaded correctly.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Define the description of command line arguments.
$optsdesc = [
    "region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // The region where the bucket is located. This parameter is required.
    "endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // The endpoint. This parameter is optional.
    "bucket" => ['help' => 'The name of the bucket', 'required' => True], // The bucket name. This parameter is required.
    "key" => ['help' => 'The name of the object', 'required' => True], // The object name. This parameter is required.
];

// Transform the argument descriptions into the long option format required by getopt.
// Add a colon (:) after each argument to indicate that the argument requires a value.
$longopts = \array_map(function ($key) {
    return "$key:";
}, array_keys($optsdesc));

// Parse the command line arguments.
$options = getopt("", $longopts);

// Verify that all required arguments are specified.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help']; // Obtain the help information of the argument.
        echo "Error: the following arguments are required: --$key, $help" . PHP_EOL;
        exit(1); // If a required argument is missing, exit the program.
    }
}

// Fetch values from the parsed arguments.
$region = $options["region"]; // The region where the bucket is located.
$bucket = $options["bucket"]; // The bucket name.
$key = $options["key"];       // The object name.

// Load credentials from environment variables.
// Use EnvironmentVariableCredentialsProvider to read the Access Key ID and Access Key Secret from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Use the default configurations of the SDK.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider); // Set the credential provider.
$cfg->setRegion($region); // Set the region where the bucket is located.
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]); // If an endpoint is provided, set the endpoint.
}

// Create an OSS client instance.
$client = new Oss\Client($cfg);

// Create a DeleteObjectRequest object to delete the specified object.
$request = new Oss\Models\DeleteObjectRequest(
            bucket: $bucket,
            key: $key,
            versionId:"yourversionid", // Specify the version number of the object to be deleted.
);

// Execute the delete object operation.
$result = $client->deleteObject($request);

// Print the deletion result.
// Output the HTTP status code and request ID to verify whether the deletion is successful.
printf(
    'status code:' . $result->statusCode . PHP_EOL . // The HTTP status code. For example, 204 indicates that the deletion is successful.
    'request id:' . $result->requestId . PHP_EOL     // The request ID, which is used to debug or track requests.
);

ossutil

To delete objects from a versioning-enabled bucket by using ossutil, see rm (delete).

REST API

You can also call the REST API directly. DeleteObject.

Restore objects

When versioning is enabled, OSS retains all versions of objects. You can restore a previous version to make it the current version.

You can restore a previous version in two ways:

  • Copy the previous version of the object

    The copied version becomes the current version, and all existing versions are retained.

    As the figure shows, copying a previous version (ID=222222) to the same bucket creates a new version (ID=444444) as the current version. The original version (ID=222222) is also retained.

  • Permanently delete the current version of the object

    As the following figure shows, permanently deleting the current version (ID=222222) by specifying its version ID makes the next most recent version (ID=111111) current.

Important

A permanently deleted version cannot be recovered. We recommend restoring previous versions by copying them.

Use the OSS console

  1. Log on to the OSS console.

  2. In the left-side navigation pane, click Buckets. On the Buckets page, find and click the desired bucket.

  3. In the left-side navigation tree, choose Object Management > Objects.

  4. On the Objects page, click Show to the right of Previous Versions.

  5. Restore a previous version of an object.

    Important

    You can restore only one object version at a time. A delete marker cannot be restored.

    • To restore a single object

      In the Actions column of the desired version, click Restore.

    • To restore multiple objects

      Select the desired previous versions, click Restore at the bottom of the page, and then click OK in the dialog box that appears.

Use the OSS SDK

The following code copies a specific version in a versioning-enabled bucket. For other SDKs, see SDK overview.

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
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";
        // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the name of the source bucket. 
        String sourceBucketName = "srcexamplebucket";
        // Specify the full path of the source object. Do not include the bucket name in the full path. 
        String sourceObjectName = "srcexampleobject.txt";
        // Specify the name of the destination bucket. The destination bucket must be located in the same region as the source bucket. 
        String destinationBucketName = "desexamplebucket";
        // Specify the full path of the destination object. Do not include the bucket name in the full path. 
        String destinationObjectName = "desexampleobject.txt";
        String versionId  = "CAEQMxiBgICAof2D0BYiIDJhMGE3N2M1YTI1NDQzOGY5NTkyNTI3MGYyMzJm****";
        // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
        String region = "cn-hangzhou";

        // Create an OSSClient instance.
        // Call the shutdown method to release resources when the OSSClient is no longer in use. 
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        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();
            }
        }
    }
}
const OSS = require('ali-oss');

const client = new OSS({
  // Set yourregion to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to oss-cn-hangzhou.
  region: 'yourregion',
  // Obtain access credentials from environment variables. Before running this code sample, make sure the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
  authorizationV4: true,
  // Set yourbucketname to the name of the bucket.
  bucket: 'yourbucketname'
});

// Specify the versionId of the source object.
const versionId = 'versionId';
// Specify the source object.
const srcObject = 'srcObject.txt';
// Specify the source bucket.
const srcBucket = 'srcBucket';
// Specify the destination object.
const targetObject = 'targetObject.txt';
async function Copy() {
  try {
    const result = await client.copy(targetObject, srcObject, srcBucket, {
      meta: {
        versionId: versionId
      }
    });

    console.log(result);
  } catch (error) {
    console.error(error);
  }
}

Copy()
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";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// 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. 
var sourceObject = "yourSourceObjectName";
// Specify the name of the destination bucket. The destination bucket must be located 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. 
var targetObject = "yourDestObjectName";
// Specify the version ID of the source object. 
var versionid = "yourArchiveObjectVersionid";
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
const string region = "cn-hangzhou";

// Create a ClientConfiguration instance and modify the default parameters based on your requirements.
var conf = new ClientConfiguration();

// Use the signature algorithm V4.
conf.SignatureVersion = SignatureVersion.V4;

// Create an OSSClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);
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 OSS account information. */
            
    /* Set Endpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set Endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
    std::string Endpoint = "yourEndpoint";
    /* Set Region to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set Region to cn-hangzhou. */
    std::string Region = "yourRegion";
    /* Specify the name of the source bucket. Example: srcexamplebucket. */
    std::string SourceBucketName = "srcexamplebucket";
    /* Specify the name of the destination bucket, which must be in the same region as the source bucket. Example: destbucket. */
    std::string CopyBucketName = "destbucket";
    /* Specify the full path of the source object. The full path cannot contain the bucket name. Example: srcdir/scrobject.txt. */
    std::string SourceObjectName = "srcdir/scrobject.txt";
    /* Specify the full path of the destination object. The full path cannot contain the bucket name. Example: destdir/destobject.txt. */
    std::string CopyObjectName = "destdir/destobject.txt";


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

    ClientConfiguration conf;
    conf.signatureVersion = SignatureVersionType::V4;
    /* Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);
    client.SetRegion(Region);

    CopyObjectRequest request(CopyBucketName, CopyObjectName);
    request.setCopySource(SourceBucketName, SourceObjectName);
    /* Specify the version ID of the source object. */
    request.setVersionId("yourSourceObjectVersionId");

    /* Copy the specified version of the 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 network resources. */
    ShutdownSdk();
    return 0;
}
package main

import (
	"context"
	"flag"
	"log"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Define global variables.
var (
	region         string // Region in which the object is stored.
	srcBucketName  string // Name of the source bucket.
	srcObjectName  string // Name of the source object.
	destBucketName string // Name of the destination bucket.
	destObjectName string // Name of the destination object.
)

// Specify the init function used to initialize command line parameters.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&srcBucketName, "src-bucket", "", "The name of the source bucket.")
	flag.StringVar(&srcObjectName, "src-object", "", "The name of the source object.")
	flag.StringVar(&destBucketName, "dest-bucket", "", "The name of the destination bucket.")
	flag.StringVar(&destObjectName, "dest-object", "", "The name of the destination object.")
}

func main() {
	// Parse command line parameters.
	flag.Parse()

	// Check whether the name of the source bucket is specified.
	if len(srcBucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, source bucket name required")
	}

	// Check whether the region is specified.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// If the name of the destination bucket is not specified, the name of the source bucket will be used.
	if len(destBucketName) == 0 {
		destBucketName = srcBucketName
	}

	// Check whether the name of the source object is specified.
	if len(srcObjectName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, source object name required")
	}

	// Check whether the name of the destination object is specified.
	if len(destObjectName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, destination object name required")
	}

	// Load the default configurations and specify the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSS client.
	client := oss.NewClient(cfg)

	// Create a copy request.
	copyRequest := &oss.CopyObjectRequest{
		Bucket:           oss.Ptr(destBucketName),            // Name of the destination bucket.
		Key:              oss.Ptr(destObjectName),            // Name of the destination object.
		SourceKey:        oss.Ptr(srcObjectName),             // Name of the source object.
		SourceBucket:     oss.Ptr(srcBucketName),             // Name of the source bucket.
		SourceVersionId:  oss.Ptr("yourVersionId"),           // Specify the actual version ID of the source object.
		StorageClass:     oss.StorageClassStandard,           // Set the storage class to Standard.
		TaggingDirective: oss.Ptr("Replace"),                 // Tags of the source object are not copied.
		Tagging:          oss.Ptr("tag1=value1&tag2=value2"), // Specify the actual tags of the destination object.
	}

	// Perform the operation and process the result.
	copyResult, err := client.CopyObject(context.TODO(), copyRequest)
	if err != nil {
		log.Fatalf("failed to copy object: %v", err)
	}

	// Display the result.
	log.Printf("copy object result versionId:%#v\n", *copyResult.VersionId)

}
<?php

// Include the autoload file to load dependencies.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Specify descriptions for command line parameters.
$optsdesc = [
    "region" => ['help' => The region in which the bucket is located.', 'required' => True], // (Required) Specify the region in which the bucket is located.
    "endpoint" => ['help' => The domain names that other services can use to access OSS.', 'required' => False], // (Optional) Specify the endpoint that can be used by other services to access OSS.
    "bucket" => ['help' => The name of the bucket, 'required' => True], // (Required) Specify the name of the destination bucket.
    "key" => ['help' => The name of the object, 'required' => True], // (Required) Specify the name of the destination object.
    "src-bucket" => ['help' => 'The name of the source bucket', 'required' => False], // (Optional) Specify the name of the source bucket.
    "key" => ['help' => The name of the object, 'required' => True], // (Required) Specify the name of the source object.
];

// Convert the parameter descriptions to a long options list required by getopt.
// Add a colon (:) to the end of each parameter to indicate that a value is required.
$longopts = \array_map(function ($key) {
    return "$key:";
}, array_keys($optsdesc));

// Parse the command line parameters.
$options = getopt("", $longopts);

// Check whether the required parameters are configured.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help']; // Obtain the help information about the parameters.
        echo "Error: the following arguments are required: --$key, $help" . PHP_EOL;
        exit(1); // If the required parameters are not configured, exit the program.
    }
}

// Obtain values from the parsed parameters.
$region = $options["region"]; // The region in which the bucket is located.
$bucket = $options["bucket"]; // The name of the destination bucket.
$key = $options["key"]; // The name of destination object.
$srcKey = $options["src-key"]; // The name of the source object.

// Obtain access credentials from environment variables.
// Obtain the AccessKey ID and AccessKey secret from the EnvironmentVariableCredentialsProvider environment variable.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Use the default configurations of the SDK.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider); // Specify the credential provider.
$cfg->setRegion($region); // Specify the region in which the bucket is located.
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]); // Specify the endpoint if an endpoint is provided.
}

// Create an OSSClient instance.
$client = new Oss\Client($cfg);

// Create a CopyObjectRequest object to copy the source object.
$request = new Oss\Models\CopyObjectRequest(
            bucket: $bucket,
            key: $key,
            sourceVersionId: "yourVersionId",// Specify the version ID of the source object.
);

if (!empty($options["src-bucket"])) {
    $request->sourceBucket = $options["src-bucket"]; // If the source bucket name is provided, specify the sourceBucket parameter.
}
$request->sourceKey = $srcKey; // Specify the name of the source object.

// Perform the object copy operation.
$result = $client->copyObject($request);

// Display the object copy result.
printf(
    'status code:' . $result->statusCode . PHP_EOL . // The HTTP status code. For example, HTTP status code 200 indicates that the request is successful.
    'request id:' . $result-> requestId. PHP_EOL //  The request ID, which is used to debug or trace a request.
);
import argparse
import alibabacloud_oss_v2 as oss

# Create a command-line argument parser and describe the purpose of the script: copy an object in a bucket.
parser = argparse.ArgumentParser(description="copy object sample")

# Define command-line arguments, including the required region, destination bucket name, source bucket name, destination object name, source object name, source object version ID, and optional endpoint.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
parser.add_argument('--bucket', help='The name of the destination bucket.', required=True)
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
parser.add_argument('--key', help='The name of the destination object.', required=True)
parser.add_argument('--source_key', help='The name of the source object.', required=True)
parser.add_argument('--source_bucket', help='The name of the source bucket.', required=True)
parser.add_argument('--source_version_id', help='The version ID of the source object.',required=True)

def main():
    # Parse command-line arguments to obtain the values entered by the user.
    args = parser.parse_args()

    # Load access credential information from environment variables for identity verification.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Use the default SDK configurations to create a configuration object and set the authentication provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider

    # Set the region property of the configuration object based on the command-line arguments.
    cfg.region = args.region

    # If a custom endpoint is provided, update the endpoint property in the configuration object.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Use the preceding configurations to initialize the OSS client and prepare for interaction with OSS.
    client = oss.Client(cfg)

    # Send a request to copy the specified object.
    result = client.copy_object(oss.CopyObjectRequest(
        bucket=args.bucket,  # Destination bucket name.
        key=args.key,  # Destination object name.
        source_key=args.source_key,  # Source object name.
        source_bucket=args.source_bucket,  # Source bucket name.
        source_version_id=args.source_version_id,  # Version ID of the source object.
    ))

    # Print the information about the operation result to confirm the request status.
    print(f'status code: {result.status_code},'
          f' request id: {result.request_id},'
          f' version id: {result.version_id},'
          f' hash crc64: {result.hash_crc64},'
          f' source version id: {result.source_version_id},'
          f' server side encryption: {result.server_side_encryption},'
          f' server side data encryption: {result.server_side_data_encryption},'
          f' last modified: {result.last_modified},'
          f' etag: {result.etag},'
          )

# When this script is directly executed, call the main function to start the processing logic.
if __name__ == "__main__":
    main()  # The entry point of the script. The program flow starts here.

Use ossutil

To restore a previous version by using ossutil, see revert (restore versions).

Use RESTful APIs

You can also call the REST API directly. CopyObject.