If 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:
The 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.
OSS generates a unique version ID for the object uploaded to a versioning-enabled bucket when you call operations such as PutObject, PostObject, CopyObject, and MultipartUpload.
This following figure shows an example. In this example, the PutObject operation is called to upload an object whose key is example.jpg to a versioning-enabled bucket. OSS generates the unique version ID 111111 for the object.
When you call the PutObject operation to upload an object that has the same key as the existing example.jpg object, OSS generates a new version with a unique version ID 222222 for the object and stores the new version as the current version of the object. Version 111111 is stored as a previous version. When you call the PutObject operation to upload an object that has the same key again, OSS generates a new version with a unique version ID 333333 for the object and stores the new version as the current version of the object. Versions 111111 and 222222 are stored as previous versions, as shown in the following figure.
Use the OSS console
Log on to the OSS console.
In the left-side navigation pane, click Buckets. On the Buckets page, find and click the desired bucket.
In the left-side navigation tree, choose Object Management > Objects.
On the Objects page, click Upload Object.
On the Upload Object page, configure the parameters.
Configure the basic settings. The following table describes the parameters.
Parameter
Description
Upload To
Specify the directory in which an object is stored after the object is uploaded to the bucket.
Current Directory: The object is uploaded to the current directory.
Specified Directory: The object is uploaded to the specified directory. Enter the name of the directory. If you enter a directory name that does not exist in the bucket, OSS automatically creates the directory and uploads the object to the directory.
The directory name must meet the following conventions:
The name must be 1 to 254 characters in length and can contain characters that are encoded in UTF-8.
The name cannot start with a forward slash (/) or backslash (\).
The name cannot contain consecutive forward slashes (/).
The name cannot be two consecutive periods (
..
).
Object ACL
Specify the ACL of the object.
Inherited from Bucket: The ACL of the object is the same as that of the bucket.
Private: Only the object owner and authorized users can read and write the object. Other users cannot access the object.
Public Read: Only the object owner or authorized users can read and write the object. Other users, including anonymous users, can only read the object. If you set the File ACL parameter to this value, the object can be read by all users. This may result in data leaks and unexpected fees. Proceed with caution.
Public Read/Write: All users, including anonymous users, can read and write the objects to upload. This may result in data leaks and unexpected fees. If a user writes prohibited data or information to the object, your legitimate interests and rights may be infringed. We recommend that you do not set the Object ACL parameter to Public Read/Write unless necessary.
For more information about object ACLs, see Object ACLs.
Files to Upload
The files or directories that you want to upload.
You can click Select Files to select a local file or click Select Folders to select a directory. You can also drag the local file or directory that you want to upload to the Files to Upload section.
If the selected directory contains a local file that you do not want to upload, find the local file in the file list in the Files to Upload section and click Remove in the Actions column to remove the file.
ImportantIf you upload a local file that has the same name as an existing object in OSS to an unversioned bucket, the uploaded object overwrites the existing object.
If you upload a local file that has the same name as an existing object in OSS to a versioning-enabled bucket, the existing object becomes a previous version, and the uploaded object becomes the current version.
Optional: Click the icon to the right of Advanced Settings to configure the advanced settings, such as the Storage Class and Encryption Method parameters. The following table describes the parameters.
Parameter
Description
Storage Class
Specify the storage class of the object. Valid values:
Inherited from Bucket (default): The storage class of the object is the same as that of the bucket.
Standard: provides highly reliable, highly available, and high-performance storage services that can process frequent data access. Standard is suitable for various business applications, such as social networking applications, image, audio, and video resource sharing applications, large websites, and big data analytics.
IA: provides highly durable storage services at lower prices than Standard. IA has a minimum billable size of 64 KB and a minimum billable storage duration of 30 days. You can access IA objects in real time. You are charged data retrieval fees when you access IA objects. IA is suitable for data that is infrequently accessed, such as data accessed once or twice a month.
Archive: provides highly durable storage services at lower prices than IA. Archive has a minimum billable size of 64 KB and a minimum billable storage duration of 60 days. You can access an Archive object after it is restored or real-time access of Archive objects is enabled. The amount of time that is required to restore an Archive object is approximately one minute. You are charged data retrieval fees if you restore an Archive object. If you access an Archive object after real-time access of Archive objects is enabled, you are charged Archive data retrieval fees based on the size of the Archive object. Archive is suitable for data that needs to be stored for a long period of time, such as archival data, medical images, scientific materials, and video footage.
Cold Archive: provides highly durable storage services at lower prices than Archive. Cold Archive has a minimum billable size of 64 KB and a minimum billable storage duration of 180 days. You must restore a Cold Archive object before you can access the object. The amount of time that is required to restore a Cold Archive object varies based on the object size and the restoration mode. You are charged data retrieval fees and API operation calling fees when you restore a Cold Archive object. Cold Archive is suitable for storing cold data over an ultra-long period of time, such as data that must be retained for an extended period of time due to compliance requirements, raw data that is accumulated over an extended period of time in the big data and AI fields, retained media resources in the film and television industries, and archived videos from the online education industry.
Deep Cold Archive: provides highly durable storage services at lower prices than Cold Archive. Deep Cold Archive has a minimum billable size of 64 KB and a minimum billable storage duration of 180 days. You must restore a Deep Cold Archive object before you can access it. The amount of time that is required to restore a Deep Cold Archive object varies based on the object size and restoration mode. You are charged data retrieval fees and API operation calling fees when you restore a Deep Cold Archive object. Deep Cold Archive is suitable for storing extremely cold data for a long period of time, such as raw data that is accumulated over an extended period of time in the big data and AI fields, media data that requires long-term retention, data that must be retained for a long period of time due to regulatory and policy compliance requirements, and data that requires tape-based retention.
For more information about storage classes, see Overview.
Encryption Method
Specify the server-side encryption method for the object. Valid values:
Inherited from Bucket (default): The encryption method of the object is the same as that of the bucket.
OSS-Managed: The keys managed by OSS are used to encrypt objects in the bucket. OSS uses keys to encrypt objects. OSS also uses master keys to encrypt cryptographic keys.
KMS: The default customer master key (CMK) stored in Key Management Service (KMS) or a specified CMK is used to encrypt and decrypt data.
Before you can use KMS to encrypt data, you must activate KMS. For more information, see Purchase a dedicated KMS instance.
The following items describe the KMS-managed CMK:
Format:
<alias>(CMK ID)
.<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 CMK managed by KMS is used to generate keys for object encryption and decryption.
alias/<cmkname>(CMK ID): A custom CMK is used to generate keys for object encryption. The CMK ID is recorded in the metadata of the encrypted objects. Objects are decrypted when they are downloaded by users who have the decryption permissions.
<cmkname>
is the optional name of the CMK that you configured when you created the CMK.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. For more information, see Create a CMK.
Encryption Algorithm: Only AES-256 is supported.
User-defined Metadata
Specify the metadata that you want to add for the object. You can add multiple user metadata headers for an object. However, the total size of user metadata cannot exceed 8 KB. When you add user metadata, the user metadata headers must contain the
x-oss-meta-
prefix and values must be specified. Example: x-oss-meta-location:hangzhou.Click Upload Object.
You can view the upload progress of the objects on the Upload Tasks tab of the Upload Tasks panel.
Use OSS SDKs
The following sample code provides examples on how to perform a simple upload to upload an object to a versioning-enabled bucket by using OSS SDKs for common programming languages. For more information about how to perform a simple upload to upload an object to a versioning-enabled bucket by using OSS SDKs for other programming languages, see Overview.
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.auth.*;
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";
// 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";
// Create an OSSClient instance.
OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);
try {
// In this example, a string is uploaded as an object.
String content = "Hello OSS";
PutObjectResult result = ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(content.getBytes()));
// Display 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\Credentials\EnvironmentVariableCredentialsProvider;
use OSS\OssClient;
use OSS\CoreOssException;
// 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.
$provider = new EnvironmentVariableCredentialsProvider();
// In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint.
$endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
$bucket= "<yourBucketName>";
// Specify the full path of the object. Do not include the bucket name in the full path. Example: example/test.txt.
$object = "<yourObjectName>";
$content = "hello world";
$config = array(
"provider" => $provider,
"endpoint" => $endpoint,
);
$ossClient = new OssClient($config);
try {
// Upload the object to a versioned bucket.
$ret = $ossClient->putObject($bucket, $object, $content);
// Display the version ID of the 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',
// 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,
// 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();
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
# 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.
auth = oss2.ProviderAuth(EnvironmentVariableCredentialsProvider())
# Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
# Specify the name of the bucket.
bucket = oss2.Bucket(auth, 'https://oss-cn-hangzhou.aliyuncs.com', 'yourBucketName')
# Upload the object.
result = bucket.put_object('yourObjectName', 'content of object')
# Display the returned HTTP status code.
print('http response code: {0}'.format(result.status))
# Display the version ID of the uploaded object.
print('put object version:', result.versionid)
using System.Text;
using Aliyun.OSS;
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
var endpoint = "yourEndpoint";
// 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 = "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 local file.
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() {
// 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.
provider, err := oss.NewEnvironmentVariableCredentialsProvider()
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Create an OSSClient instance.
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint.
client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider))
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Specify the name of the bucket.
bucket, err := client.Bucket("yourBucketName")
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
var retHeader http.Header
// Upload the string. Use oss.GetResponseHeader to obtain the returned header.
// Specify the full path of the object. Do not include the bucket name in the full path.
err = bucket.PutObject("yourObjectName", strings.NewReader("yourObjectValue"), oss.GetResponseHeader(&retHeader))
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Display the value of the x-oss-version-id header.
fmt.Println("x-oss-version-id:", oss.GetVersionId(retHeader))
}
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;
int main(void)
{
/* Initialize information about the account that is used to access OSS. */
/* Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
std::string Endpoint = "yourEndpoint";
/* Specify the name of the bucket. Example: examplebucket. */
std::string BucketName = "examplebucket";
/* Specify the full path of the object. Do not include the bucket name in the full path of the object. Example: exampledir/exampleobject.txt. */
std::string ObjectName = "exampledir/exampleobject.txt";
/* Initialize resources such as network resources. */
InitializeSdk();
ClientConfiguration conf;
/* 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);
std::shared_ptr<std::iostream> content = std::make_shared<std::stringstream>();
*content << "test cpp sdk";
PutObjectRequest request(BucketName, ObjectName, content);
/* Upload the object. */
auto outcome = client.PutObject(request);
if (outcome.isSuccess()) {
std::cout << "versionid:" << outcome.result().VersionId() << std::endl;
}
else {
/* Handle exceptions. */
std::cout << "PutObject fail" <<
",code:" << outcome.error().Code() <<
",message:" << outcome.error().Message() <<
",requestId:" << outcome.error().RequestId() << std::endl;
return -1;
}
/* Release resources such as network resources. */
ShutdownSdk();
return 0;
}
Use ossutil
For more information about how to perform a simple upload to upload an object to a versioning-enabled bucket by using ossutil, see Upload objects.
Use the RESTful API
If your program requires more custom options, you can call RESTful API operations. To directly call an API operation, you must include the signature calculation in your code. For more information, see PutObject.
List objects
You can call the GetBucketVersions (ListObjectVersions) operation to query information about all object versions in a versioning-enabled bucket, including delete markers.
Compared with the GetBucketVersions (ListObjectVersions) operation, the GetBucket (ListObject) operation returns only the current object versions that are not delete markers in a bucket.
Up to 1,000 object versions can be returned for a GetBucketVersions (ListObjectVersions) request. You can send multiple GetBucketVersions (ListObjectVersions) requests to obtain all object versions in a versioning-enabled bucket.
For example, a bucket contains two objects whose keys are example.jpg and photo.jpg. The example.jpg object has 900 versions. The photo.jpg object has 500 versions. If you send a GetBucketVersions (ListObjectVersions) request, 900 versions of the example.jpg object and 100 versions of the photo.jpg object are returned. The versions are returned in alphabetical order of object keys first and then in the order of time when the versions were generated.
All object versions, including delete markers, are returned when the GetBucketVersions (ListObjectVersions) operation is called, as shown in the following figure. Only current object versions that are not delete markers are returned when the GetBucket (ListObject) operation is called. Therefore, only the current version of the photo.jpg object, whose version ID is 444444, is returned.
Use the OSS console
Log on to the OSS console.
In the left-side navigation pane, click Buckets. On the Buckets page, click the name of the bucket in which the objects you want to list are stored.
The current page displays the current versions of all objects in the bucket by page, excluding delete markers. To view all versions of all objects in the bucket, including delete markers, click Show to the right of Previous Versions on the Objects page.
Use OSS SDKs
The following sample code provides examples on how to list objects in a versioning-enabled bucket by using OSS SDKs for common programming languages. For more information about how to list objects by using OSS SDKs for other programming languages, see Overview.
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.auth.*;
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";
// 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";
// Create an OSSClient instance.
OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);
try {
// List the versions of all objects, including delete markers in the bucket.
String nextKeyMarker = null;
String nextVersionMarker = null;
VersionListing versionListing = null;
do {
ListVersionsRequest listVersionsRequest = new ListVersionsRequest()
.withBucketName(bucketName)
.withKeyMarker(nextKeyMarker)
.withVersionIdMarker(nextVersionMarker);
versionListing = ossClient.listVersions(listVersionsRequest);
for (OSSVersionSummary ossVersion : versionListing.getVersionSummaries()) {
System.out.println("key name: " + ossVersion.getKey());
System.out.println("versionid: " + ossVersion.getVersionId());
System.out.println("Is latest: " + ossVersion.isLatest());
System.out.println("Is delete marker: " + ossVersion.isDeleteMarker());
}
nextKeyMarker = versionListing.getNextKeyMarker();
nextVersionMarker = versionListing.getNextVersionIdMarker();
} while (versionListing.isTruncated());
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
} catch (ClientException ce) {
System.out.println("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
System.out.println("Error Message:" + ce.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
}
<?php
if (is_file(__DIR__ . '/../autoload.php')) {
require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
require_once __DIR__ . '/../vendor/autoload.php';
}
use OSS\Credentials\EnvironmentVariableCredentialsProvider;
use OSS\OssClient;
use OSS\CoreOssException;
// 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.
$provider = new EnvironmentVariableCredentialsProvider();
// 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.
$endpoint = "yourEndpoint";
// Specify the name of the bucket. Example: examplebucket.
$bucket= "examplebucket";
$config = array(
"provider" => $provider,
"endpoint" => $endpoint,
);
$ossClient = new OssClient($config);
try{
$option = array(
OssClient::OSS_KEY_MARKER => null,
OssClient::OSS_VERSION_ID_MARKER => null
);
$bool = true;
while ($bool){
$result = $ossClient->listObjectVersions($bucket,$option);
// Display information about the listed versions of the 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 information about the listed versions of the 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;
}
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 the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
// Specify the name of the bucket.
bucket: 'yourbucketname'
});
// List the versions of all objects in the bucket, 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();
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
# 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.
auth = oss2.ProviderAuth(EnvironmentVariableCredentialsProvider())
# Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
# Specify the name of the bucket.
bucket = oss2.Bucket(auth, 'https://oss-cn-hangzhou.aliyuncs.com', 'yourBucketName')
# Call the list_object_versions operation to list the versions of objects in a versioning-enabled bucket.
# List the versions of all objects, including delete markers in the bucket.
result = bucket.list_object_versions()
# List the versions of all objects in the bucket.
next_key_marker = None
next_versionid_marker = None
while True:
result = bucket.list_object_versions(key_marker=next_key_marker, versionid_marker=next_versionid_marker)
# Display the versions of the listed objects.
for version_info in result.versions:
print('version_info.versionid:', version_info.versionid)
print('version_info.key:', version_info.key)
print('version_info.is_latest:', version_info.is_latest)
# Display the versions of the listed delete markers.
for del_maker_Info in result.delete_marker:
print('del_maker.key:', del_maker_Info.key)
print('del_maker.versionid:', del_maker_Info.versionid)
print('del_maker.is_latest:', del_maker_Info.is_latest)
is_truncated = result.is_truncated
# Check whether all versions of all objects in the bucket are listed. If 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() {
// 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.
provider, err := oss.NewEnvironmentVariableCredentialsProvider()
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Create an OSSClient instance.
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint.
client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider))
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Specify the name of the bucket.
bucketName := "examplebucket"
bucket,err := client.Bucket(bucketName)
if err != nil {
HandleError(err)
}
// List the versions of all objects including delete markers in the bucket.
keyMarker := oss.KeyMarker("")
// The VersionIdMarker parameter is configured together with the KeyMarker parameter to specify the position from which the list operation starts.
versionIdMarker := oss.VersionIdMarker("")
for {
lor, err := bucket.ListObjectVersions(keyMarker,versionIdMarker)
if err != nil {
HandleError(err)
}
// Display the version IDs of the objects.
for _, dirName := range lor.ObjectVersions{
fmt.Println("Versionid:",dirName.VersionId)
fmt.Println("Key:",dirName.Key)
fmt.Println("Is Latest",dirName.IsLatest)
}
// View the versions of the listed delete markers.
for _, marker := range lor.ObjectDeleteMarkers {
fmt.Println(marker.VersionId)
fmt.Println(marker.Key)
}
// Check whether the required versions are listed. If the versions are incompletely listed, the list operation continues. If the versions are completely listed, the list operation stops.
keyMarker = oss.KeyMarker(lor.NextKeyMarker)
versionIdMarker = oss.VersionIdMarker(lor.NextVersionIdMarker)
if !lor.IsTruncated {
break
}
}
}
Use ossutil
For more information about how to list objects in a versioning-enabled bucket, see List objects.
Use the RESTful API
If your program requires more custom options, you can call RESTful API operations. To directly call an API operation, you must include the signature calculation in your code. For more information, see ListObjectVersions (GetBucketVersions).
Download objects
You can download the current version or a specific version of an object from a versioning-enabled bucket.
By default, if a GetObject request in which no version ID is specified is initiated to download an object, the current version of the object is returned. In the following figure, the current version of the object whose version ID is 333333 is returned.
If a GetRequest request in which no version ID is specified is initiated to download an object and the current version of the object is a delete marker, 404 Not Found is returned.
To download a specific version of an object, you must specify the version ID in the GetObject request. In the following figure, a GetObject request in which the version ID 222222 is specified is initiated to download the object whose version ID is 222222.
Use the OSS console
Log on to the OSS console.
In the left-side navigation pane, click Buckets. On the Buckets page, find and click the desired bucket.
In the left-side navigation tree, choose Object Management > Objects.
On the Objects page, click Show to the right of Previous Versions.
Click the version that you want to download. In the panel that appears, click Download to the right of Object URL.
Use OSS SDKs
The following sample code provides examples on how to download objects from a versioning-enabled bucket by using OSS SDKs for common programming languages. For more information about how to download objects by using OSS SDKs for other programming languages, see Overview.
In the Python example, Python 2 is used.
<?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;
// 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.
$accessKeyId = getenv("OSS_ACCESS_KEY_ID");
$accessKeySecret = getenv("OSS_ACCESS_KEY_SECRET");
// In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint.
$endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
$bucket= "<yourBucketName>";
// Specify the full path of the object. The full path of the object cannot contain 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 specified version of the object.
$content = $ossClient->getObject($bucket, $object, array(OssClient::OSS_VERSION_ID => $versionId));
print($content);
} catch(OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
const OSS = require('ali-oss');
const client = new OSS({
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou.
region: 'yourregion',
// 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,
// Specify the name of the bucket.
bucket: 'yourbucketname'
});
async function get() {
// Specify the name of the object.
const result = await client.get('filename', {
// Display the version ID of the downloaded object.
versionId: 'versionid',
});
console.log(result.content);
}
get();
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
# 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.
auth = oss2.ProviderAuth(EnvironmentVariableCredentialsProvider())
# Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
# Specify the name of the bucket.
bucket = oss2.Bucket(auth, 'https://oss-cn-hangzhou.aliyuncs.com', 'yourBucketName')
# Download a specific 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 that is 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!")
package main
import (
"fmt"
"net/http"
"os"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
func main() {
/// 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.
provider, err := oss.NewEnvironmentVariableCredentialsProvider()
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Create an OSSClient instance.
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint.
client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider))
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Specify the name of the bucket.
bucket, err := client.Bucket("<yourBucketName>")
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
var retHeader http.Header
// Download the version whose ID is yourObjectVersionId to the cache.
// Specify the full path of the object. Do not include the bucket name in the full path.
_, err = bucket.GetObject("youObjectName", oss.VersionId("yourObjectVersionId"), oss.GetResponseHeader(&retHeader))
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Display the value of x-oss-version-id.
fmt.Println("x-oss-version-id:", oss.GetVersionId(retHeader))
}
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;
int main(void)
{
/* Initialize information about the account that is used to access 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. */
std::string Endpoint = "yourEndpoint";
/* Specify the name of the bucket. Example: examplebucket. */
std::string BucketName = "examplebucket";
/* Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt. */
std::string ObjectName = "exampledir/exampleobject.txt";
/* Initialize resources such as network resources. */
InitializeSdk();
ClientConfiguration conf;
/* 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);
/* Download the object into memory. */
GetObjectRequest request(BucketName, ObjectName);
request.setVersionId("yourObjectVersionId");
auto outcome = client.GetObject(request);
if (outcome.isSuccess()) {
std::cout << "getObjectToBuffer" << " success, Content-Length:" << outcome.result().Metadata().ContentLength() << std::endl;
/* Read the content of the downloaded object. */
std::string content;
*(outcome.result().Content()) >> content;
std::cout << "getObjectToBuffer" << "content:" << content << std::endl;
/* Display the version ID of the downloaded object. */
std::cout << "versionid:" << outcome.result().VersionId() << std::endl;
}
else {
/* Handle exceptions. */
std::cout << "getObjectToBuffer fail" <<
",code:" << outcome.error().Code() <<
",message:" << outcome.error().Message() <<
",requestId:" << outcome.error().RequestId() << std::endl;
return -1;
}
/* Release resources such as network resources. */
ShutdownSdk();
return 0;
}
Use ossutil
For more information about how to download objects from a versioning-enabled bucket by using ossutil, see Download objects.
Use the RESTful API
If your program requires more custom options, you can call RESTful API operations. To directly call an API operation, you must include the signature calculation in your code. For more information, see GetObject.
Delete objects
You can specify a version ID of an object in the DeleteObject request or configure lifecycle rules to permanently delete a version of an object in a versioning-enabled bucket. If you do not specify a version ID in the DeleteObject request, OSS adds a delete marker as the current version of the object.
By default, if you do not specify a version ID in the DeleteObject request, the current version and previous versions of the object are not deleted.
Do not enable OSS-HDFS and versioning for a bucket.
If OSS-HDFS and versioning are enabled for a bucket, OSS-HDFS may not work as expected. To ensure the stability of OSS-HDFS, you need to suspend versioning at the earliest opportunity and configure lifecycle rules to remove delete markers.
For more information, see How do I resolve the issue that occurs after I enable OSS-HDFS and versioning for a bucket?
In addition, you can specify the Expiration element in lifecycle rules to specify that the current versions of objects in a versioning-enabled bucket expire. 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 retain the expired current versions of objects. When the current version of an object expires based on a lifecycle rule in which the Expiration element is specified, OSS stores the current version as a previous version and adds a delete marker as the current version.
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, see Configuration elements.
The following section describes how OSS deletes an object when the version ID is specified and not specified in a 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 that you want to delete. The delete marker has a unique version ID but does not have data and ACL. A delete marker whose version ID is 444444 is added as the current version, as shown in the following figure.
If the version ID is specified in the DeleteObject request, the specified version is permanently deleted. The version whose ID is 333333 is permanently deleted, as shown in the following figure.
Use the OSS console
To minimize storage costs, we recommend that you delete the previous versions of objects that you no longer need at your earliest opportunity.
You cannot restore a previous version of an object after it is deleted. Proceed with caution.
Log on to the OSS console.
In the left-side navigation pane, click Buckets. On the Buckets page, find and click the desired bucket.
In the left-side navigation tree, choose Object Management > Objects.
On the Objects page, click Show to the right of Previous Versions.
Find the previous version of the object that you no longer need and perform the operations based on the following description:
If the previous version of the object that you want to delete is a delete marker, click Permanently Delete in the Actions column.
If the previous version of the object that you want to delete is not a delete marker, move the pointer over the icon in the Actions column and click Permanently Delete.
To delete multiple previous versions of an object, select the previous versions that you want to delete and click Permanently Delete below the object list.
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 sample code provides examples on how to delete a specific version of an object from a versioning-enabled bucket by using OSS SDKs for common programming languages. For more information about how to delete a specific version of an object by using OSS SDKs for other programming languages, see Overview.
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.auth.*;
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";
// 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****";
// Create an OSSClient instance.
OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);
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();
}
}
}
}
<?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\Credentials\EnvironmentVariableCredentialsProvider;
use OSS\OssClient;
use OSS\CoreOssException;
// 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.
$provider = new EnvironmentVariableCredentialsProvider();
// In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint.
$endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
$bucket= "<yourBucketName>";
// Specify the full path of the object. Do not include the bucket name in the full path. Example: example/test.txt.
$object = "<yourObjectName>";
$versionId = "<yourObjectVersionId>";
$config = array(
"provider" => $provider,
"endpoint" => $endpoint,
);
$ossClient = new OssClient($config);
try{
// Delete the specified version of the object.
$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',
// 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.
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
// Specify the name of the bucket.
bucket: 'yourbucketname'
});
// Specify the version ID 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();
# -*- coding: utf-8 -*-
import os
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
# 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.
auth = oss2.ProviderAuth(EnvironmentVariableCredentialsProvider())
# Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
# Specify the name of the bucket.
bucket = oss2.Bucket(auth, 'https://oss-cn-hangzhou.aliyuncs.com', 'yourBucketName')
# Specify the full path of the object. Do not include the bucket name in the full path. Example: example/test.txt.
object_name = 'yourObjectName'
# Specify the version ID of the object or delete marker that you want to delete.
params = dict()
params['versionId'] = 'yourObjectVersionIdOrDeleteMarkerVersionId'
# Delete the specific version of the object or delete marker.
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";
// 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";
// 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, objectName)
{
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"
"os"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
func main() {
/// 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.
provider, err := oss.NewEnvironmentVariableCredentialsProvider()
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Create an OSSClient instance.
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint.
client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider))
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Specify the name of the bucket.
bucket, err := client.Bucket("yourBucketName")
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Specify the full path of the object. Do not include the bucket name in the full path.
// Set yourObjectVersionId to the version ID of the object. If this parameter is specified, the object with the specified version ID is permanently deleted.
err = bucket.DeleteObject("youObjectName", 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 information about the account that is used to access 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. */
std::string Endpoint = "yourEndpoint";
/* Specify the name of the bucket. Example: examplebucket. */
std::string BucketName = "examplebucket";
/* Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt. */
std::string ObjectName = "exampledir/exampleobject.txt";
/* Initialize resources such as network resources. */
InitializeSdk();
ClientConfiguration conf;
/* 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);
/* Delete the object with the specified version ID or the object whose current version is a delete marker with the specified version ID. */
auto outcome = client.DeleteObject(DeleteObjectRequest(BucketName, ObjectName, "yourObjectVersionIdOrDeleteMarkerVersionId"));
/* If the version ID of an object is specified in the request, the value of the delete_marker header in the response is None and the value of the versionId header in the response is the version ID specified in the request. */
/* If the version ID of a delete marker is specified in the request, the value of the delete_marker header in the response is True and the value of the versionId header in the response is the version ID specified in the request. */
if (!outcome.isSuccess()) {
/* Handle exceptions. */
std::cout << "DeleteObject fail" <<
",code:" << outcome.error().Code() <<
",message:" << outcome.error().Message() <<
",requestId:" << outcome.error().RequestId() << std::endl;
return -1;
}
/* Release resources such as network resources. */
ShutdownSdk();
return 0;
}
Use ossutil
For more information about how to delete objects from a versioning-enabled bucket by using ossutil, see rm.
Use the RESTful API
If your program requires more custom options, you can call RESTful API operations. To directly call an API operation, you must include the signature calculation in your code. For more information, see DeleteObject.
Restore objects
When versioning is enabled for a bucket, all versions of objects in the bucket are retained. You can restore a specific previous version of an object as the current version.
You can restore a previous version of an object as the current version by using one of the following methods:
Call the CopyObject operation to copy the previous version of an object to the same bucket
The copied previous version becomes the current version of the object, and all versions of the object are retained.
In the following figure, a previous version whose ID is 222222 is copied to the same bucket. OSS generates a new version ID 444444 for the copied version. The copied version becomes the current version of the object. Therefore, the object has two versions that have the same content: 222222 and 444444, in which 222222 is a previous version and 444444 is the current version.
Permanently delete the current version of an 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.
We recommend that you call the CopyObject operation 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
Log on to the OSS console.
In the left-side navigation pane, click Buckets. On the Buckets page, find and click the desired bucket.
In the left-side navigation tree, choose Object Management > Objects.
On the Objects page, click Show to the right of Previous Versions.
Restore a specific previous version of an object as the current version.
ImportantYou 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 of the previous version that you want to restore.
Restore the previous versions of multiple objects
Select the versions that you want to restore and click Restore below the object list. In the message that appears, click OK.
Use OSS SDKs
The following sample code provides examples on how to copy a specific version of an object from a versioning-enabled bucket by using OSS SDKs for common programming languages. For more information about how to copy a specific version of an object by using OSS SDKs for other programming languages, see Overview.
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.auth.*;
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";
// 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****";
// Create an OSSClient instance.
OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);
try {
CopyObjectRequest copyObjectRequest = new CopyObjectRequest(sourceBucketName, sourceObjectName, destinationBucketName, destinationObjectName);
copyObjectRequest.setSourceVersionId(versionId);
CopyObjectResult copyObjectResult = ossClient.copyObject(copyObjectRequest);
System.out.println("ETag: " + copyObjectResult.getETag() + " LastModified: " + copyObjectResult.getLastModified());
System.out.println("dest object versionid: " + copyObjectResult.getVersionId());
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
} catch (ClientException ce) {
System.out.println("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
System.out.println("Error Message:" + ce.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
}
<?php
if (is_file(__DIR__ . '/../autoload.php')) {
require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
require_once __DIR__ . '/../vendor/autoload.php';
}
use OSS\Credentials\EnvironmentVariableCredentialsProvider;
use OSS\OssClient;
use OSS\CoreOssException;
// 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.
$provider = new EnvironmentVariableCredentialsProvider();
// In this example, the China (Hangzhou) region is used as the endpoint. Specify your actual endpoint.
$endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
$bucket= "<yourBucketName>";
// Specify the full path of the object. Do not include the bucket name in the full path. Example: example/test.txt.
$object = "<yourObjectName>";
$versionId = "<yourObjectVersionId>";
$to_bucket = $bucket;
$to_object = $object . '.copy';
$config = array(
"provider" => $provider,
"endpoint" => $endpoint,
);
$ossClient = new OssClient($config);
try{
// Copy the specified version of the object.
$ret = $ossClient->copyObject($bucket, $object, $to_bucket, $to_object, array(OssClient::OSS_VERSION_ID => $versionId));
print("versionId:" .$ret['x-oss-version-id']);
} catch(OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
const OSS = require('ali-oss');
const client = new OSS({
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou.
region: 'yourregion',
// 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,
// Specify the name of the bucket.
bucket: 'yourbucketname'
});
// Specify the version ID of the source object.
const versionId = 'versionId';
// Specify the source object to copy.
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()
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
# 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.
auth = oss2.ProviderAuth(EnvironmentVariableCredentialsProvider())
# Specify the name of the source bucket. Example: srcexamplebucket.
src_bucket_name = 'srcexamplebucket'
# Specify the name of the destination bucket. The destination bucket must be in the same region as the source bucket. Example: destexamplebucket.
# If you copy an object within a bucket, make sure that you specify the same bucket name for the source and destination buckets.
dest_bucket_name = 'destexamplebucket'
# Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
bucket = oss2.Bucket(auth, 'https://oss-cn-hangzhou.aliyuncs.com', dest_bucket_name)
# Specify the full path of the source object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt.
src_object_name = 'srcexampledir/exampleobject.txt'
# Specify the full path of the destination object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt.
dest_object_name = 'destexampledir/exampleobject.txt'
# Specify the version ID of the object.
versionId = 'CAEQMxiBgICAof2D0BYiIDJhMGE3N2M1YTI1NDQzOGY5NTkyNTI3MGYyMzJm****'
# Copy the specified version of the source object.
params = dict()
params['versionId'] = versionId
# Copy the source object from the source bucket to the destination bucket.
result = bucket.copy_object(src_bucket_name, src_object_name, dest_object_name, params=params)
# Display the response. If the returned value is 200, the source object is copied to the destination bucket.
print('result.status:', result.status)
using Aliyun.OSS;
using Aliyun.OSS.Common;
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
var endpoint = "yourEndpoint";
// 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";
// Create an OSSClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
try
{
var metadata = new ObjectMetadata();
metadata.AddHeader("mk1", "mv1");
metadata.AddHeader("mk2", "mv2");
var req = new CopyObjectRequest(sourceBucket, sourceObject, targetBucket, targetObject)
{
// If the value of NewObjectMetadata is null, the COPY mode is used and the metadata of the source object is copied to the destination object. If the value of NewObjectMetadata is not null, the REPLACE mode is used and the metadata of the source object overwrites the metadata of the destination object.
NewObjectMetadata = metadata,
// Specify the version ID of the object.
SourceVersionId = versionid
};
// Copy the object.
var result = client.CopyObject(req);
Console.WriteLine("Copy object succeeded, vesionid:{0}", result.VersionId);
}
catch (OssException ex)
{
Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID: {2} \tHostID: {3}",
ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
}
catch (Exception ex)
{
Console.WriteLine("Failed with error info: {0}", ex.Message);
}
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;
int main(void)
{
/* Initialize information about the account that is used to access OSS. */
/* Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
std::string Endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
/* Specify the name of the source bucket. Example: srcexamplebucket. */
std::string SourceBucketName = "srcexamplebucket";
/* Specify the name of the destination bucket. The destination bucket must be located in the same region as the source bucket. Example: destbucket. */
std::string CopyBucketName = "destbucket";
/* Specify the full path of the source object. Do not include the bucket name in the full path. Example: srcdir/scrobject.txt. */
std::string SourceObjectName = "srcdir/scrobject.txt";
/* Specify the full path of the destination object. Do not include the bucket name in the full path. Example: destdir/destobject.txt. */
std::string CopyObjectName = "destdir/destobject.txt";
/* Initialize resources, such as network resources. */
InitializeSdk();
ClientConfiguration conf;
/* 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);
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 source object. */
auto outcome = client.CopyObject(request);
if (outcome.isSuccess()) {
std::cout << "versionid:" << outcome.result().VersionId() << std::endl;
}
else {
/* Handle exceptions. */
std::cout << "CopyObject fail" <<
",code:" << outcome.error().Code() <<
",message:" << outcome.error().Message() <<
",requestId:" << outcome.error().RequestId() << std::endl;
return -1;
}
/* Release resources, such as network resources. */
ShutdownSdk();
return 0;
}
Use ossutil
For more information about how to restore a previous version of an object as the current version in a versioning-enabled bucket by using ossutil, see Copy objects.
Use the RESTful API
If your program requires more custom options, you can call RESTful API operations. To directly call an API operation, you must include the signature calculation in your code. For more information, see CopyObject.