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 {
// Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// 填写Bucket名称,例如examplebucket。
String bucketName = "examplebucket";
// 填写不包含Bucket名称在内的归档类型Object的完整路径。
String objectName = "exampledir/object";
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);
try {
ObjectMetadata objectMetadata = ossClient.getObjectMetadata(bucketName, objectName);
// 校验Object是否为归档类型Object。
StorageClass storageClass = objectMetadata.getObjectStorageClass();
if (storageClass == StorageClass.Archive) {
// 解冻Object。
ossClient.restoreObject(bucketName, objectName);
// 等待解冻完成。
Thread.sleep(1000);
objectMetadata = ossClient.getObjectMetadata(bucketName, objectName);
} while (!objectMetadata.isRestoreCompleted());
// 获取解冻Object。
OSSObject ossObject = ossClient.getObject(bucketName, objectName);
ossObject.getObjectContent().close();
} 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;
// 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
$provider = new EnvironmentVariableCredentialsProvider();
// Endpoint以华东1(杭州)为例,其他Region请按实际情况填写。
$endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
// 填写Bucket名称,例如examplebucket。
$bucket= "examplebucket";
// 填写不包含Bucket名称在内归档类型Object的完整路径,例如srcexampleobject.txt。
$object = "srcexampleobject.txt";
try {
$config = array(
"provider" => $provider,
"endpoint" => $endpoint,
$ossClient = new OssClient($config);
// 解冻文件。
$ossClient->restoreObject($bucket, $object);
} 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({
//yourRegion填写Bucket所在地域。以华东1(杭州)为例,Region填写为oss-cn-hangzhou。
region: 'yourRegion',
// 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
//填写Bucket名称,例如examplebucket。
bucket: 'examplebucket',
//填写待解冻的归档类型Object名称,例如exampleobject.txt。
client.restore('exampleobject.txt').then((res) => {
console.log(res);
}).catch(err => {
console.log(err);
})
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
from oss2.models import RestoreConfiguration
# 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
auth = oss2.ProviderAuth(EnvironmentVariableCredentialsProvider())
# yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
# 填写Bucket名称,例如examplebucket。
bucket = oss2.Bucket(auth, 'https://oss-cn-hangzhou.aliyuncs.com', 'examplebucket')
# 填写不包含Bucket名称在内的归档类型Object的完整路径。
objectName = 'yourArchiveObjectName'
# 配置解冻状态持续时间,默认为1天。本代码示例以解冻状态持续时间为2天为例。
days = 2
restore_config= RestoreConfiguration(days=days)
# 发起解冻请求。
bucket.restore_object(objectName, input=restore_config)
using Aliyun.OSS;
using Aliyun.OSS.Model;
using Aliyun.OSS.Model;
using System.Net;
using System.Text;
// yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
var endpoint = "yourEndpoint";
// 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// 填写Bucket名称。
var bucketName = "examplebucket";
// 填写不包含Bucket名称在内的归档类型Object的完整路径。
var objectName = "yourObjectName";
// 自定义Object内容。
var objectContent = "More than just cloud.";
int maxWaitTimeInSeconds = 600;
// 创建OssClient实例。
var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
// 创建归档存储空间。
var bucket = client.CreateBucket(bucketName, StorageClass.Archive);
Console.WriteLine("Create Archive bucket succeeded, {0} ", bucket.Name);
catch (Exception ex)
Console.WriteLine("Create Archive bucket failed, {0}", ex.Message);
// 上传文件并设置存储类型为归档类型。
byte[] binaryData = Encoding.ASCII.GetBytes(objectContent);
MemoryStream requestContent = new MemoryStream(binaryData);
client.PutObject(bucketName, objectName, requestContent);
Console.WriteLine("Put object succeeded, {0}", objectName);
catch (Exception ex)
Console.WriteLine("Put object failed, {0}", ex.Message);
var metadata = client.GetObjectMetadata(bucketName, objectName);
string storageClass = metadata.HttpMetadata["x-oss-storage-class"] as string;
if (storageClass != "Archive")
Console.WriteLine("StorageClass is {0}", storageClass);
return;
// 解冻归档Object。
RestoreObjectResult result = client.RestoreObject(bucketName, objectName);
Console.WriteLine("RestoreObject result HttpStatusCode : {0}", result.HttpStatusCode);
if (result.HttpStatusCode != HttpStatusCode.Accepted)
throw new OssException(result.RequestId + ", " + result.HttpStatusCode + " ,");
while (maxWaitTimeInSeconds > 0)
var meta = client.GetObjectMetadata(bucketName, objectName);
string restoreStatus = meta.HttpMetadata["x-oss-restore"] as string;
if (restoreStatus != null && restoreStatus.StartsWith("ongoing-request=\"false\"", StringComparison.InvariantCultureIgnoreCase))
break;
Thread.Sleep(1000);
// 最长等待时间减少1秒。
maxWaitTimeInSeconds--;
if (maxWaitTimeInSeconds == 0)
Console.WriteLine("RestoreObject is timeout. ");
throw new TimeoutException();
Console.WriteLine("RestoreObject is successful. ");
}
// 解冻归档文件。
RestoreObjectRequest restore = new RestoreObjectRequest();
// 填写Bucket名称,例如examplebucket。
restore.setBucketName("examplebucket");
// 填写不包含Bucket名称在内的Object完整路径,例如exampleobject.txt。
restore.setObjectKey("exampleobject.txt");
OSSAsyncTask task = oss.asyncRestoreObject(restore, new OSSCompletedCallback<RestoreObjectRequest,
RestoreObjectResult>() {
@Override
public void onSuccess(RestoreObjectRequest request, RestoreObjectResult result) {
Log.i("info", "code::"+result.getStatusCode());
@Override
public void onFailure(RestoreObjectRequest request, ClientException clientException,
ServiceException serviceException) {
Log.e("errorMessage", "error: "+serviceException.getRawMessage());
task.waitUntilFinished();
package main
import (
"fmt"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
func HandleError(err error) {
fmt.Println("Error:", err)
os.Exit(-1)
func main() {
// 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
provider, err := oss.NewEnvironmentVariableCredentialsProvider()
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
// 创建OSSClient实例。
// yourEndpoint填写Bucket对应的Endpoint,以华东1(杭州)为例,填写为https://oss-cn-hangzhou.aliyuncs.com。其它Region请按实际情况填写。
client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider))
if err != nil {
HandleError(err)
// 填写存储空间名称,例如examplebucket。
bucketName := "examplebucket"
// 填写不包含Bucket名称在内的Object的完整路径,例如exampledir/exampleobject.txt。
objectName := "exampledir/exampleobject.txt"
archiveBucket, err := client.Bucket(bucketName)
if err != nil {
HandleError(err)
// 解冻归档类型Object。
err = archiveBucket.RestoreObject(objectName)
if err != nil {
HandleError(err)
fmt.Println("ArchiveSample completed")
}
OSSRestoreObjectRequest *request = [OSSRestoreObjectRequest new];
// 填写Bucket名称,例如examplebucket。
request.bucketName = @"examplebucket";
// 填写不包含Bucket名称在内的Object完整路径,例如exampleobject.txt。
request.objectKey = @"exampleobject.txt";
OSSTask *restoreObjectTask = [client restoreObject:request];
[restoreObjectTask continueWithBlock:^id _Nullable(OSSTask * _Nonnull task) {
if (!task.error) {
NSLog(@"restore object success");
} else {
NSLog(@"restore object failed, error: %@", task.error);
return nil;
}];
#include <alibabacloud/oss/OssClient.h>
#include <thread>
#include <chrono>
#include <algorithm>
using namespace AlibabaCloud::OSS;
int main(void)
/*初始化OSS账号信息。*/
/*yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。*/
std::string Endpoint = "yourEndpoint";
/*填写Bucket名称,例如examplebucket。*/
std::string BucketName = "examplebucket";
/*填写不包含Bucket名称在内的归档类型Object的完整路径。*/
std::string ObjectName = "yourObjectName";
/*初始化网络等资源。*/
InitializeSdk();
ClientConfiguration conf;
/* 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。*/
auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
OssClient client(Endpoint, credentialsProvider, conf);
/*解冻归档Object。*/
auto outcome = client.RestoreObject(BucketName, ObjectName);
/*非归档Object不能解冻。*/
if (!outcome.isSuccess()) {
/*异常处理。*/
std::cout << "RestoreObject fail,code:" << outcome.error().Code() <<
",message:" << outcome.error().Message() <<
",requestId:" << outcome.error().RequestId() << std::endl;
return -1;
std::string onGoingRestore("ongoing-request=\"false\"");
int maxWaitTimeInSeconds = 600;
while (maxWaitTimeInSeconds > 0)
auto meta = client.HeadObject(BucketName, ObjectName);
std::string restoreStatus = meta.result().HttpMetaData()["x-oss-restore"];
std::transform(restoreStatus.begin(), restoreStatus.end(), restoreStatus.begin(), ::tolower);
if (!restoreStatus.empty() &&
restoreStatus.compare(0, onGoingRestore.size(), onGoingRestore)==0) {
std::cout << " success, restore status:" << restoreStatus << std::endl;
/*成功解冻归档Object。*/
break;
std::cout << " info, WaitTime:" << maxWaitTimeInSeconds
<< "; restore status:" << restoreStatus << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(10));
maxWaitTimeInSeconds--;
if (maxWaitTimeInSeconds == 0)
std::cout << "RestoreObject fail, TimeoutException" << std::endl;
/*释放网络等资源。*/
ShutdownSdk();
return 0;
}
#include "oss_api.h"
#include "aos_http_io.h"
/* yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。*/
const char *endpoint = "yourEndpoint";
/* 填写Bucket名称,例如examplebucket。*/
const char *bucket_name = "examplebucket";
/* 填写Object完整路径,完整路径中不能包含Bucket名称,例如exampledir/exampleobject.txt。*/
const char *object_name = "exampledir/exampleobject.txt";
void init_options(oss_request_options_t *options)
options->config = oss_config_create(options->pool);
/* 用char*类型的字符串初始化aos_string_t类型。*/
aos_str_set(&options->config->endpoint, endpoint);
/* 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。*/
aos_str_set(&options->config->access_key_id, getenv("OSS_ACCESS_KEY_ID"));
aos_str_set(&options->config->access_key_secret, getenv("OSS_ACCESS_KEY_SECRET"));
/* 是否使用了CNAME。0表示不使用。*/
options->config->is_cname = 0;
/* 用于设置网络相关参数,比如超时时间等。*/
options->ctl = aos_http_controller_create(options->pool, 0);
int main(int argc, char *argv[])
/* 在程序入口调用aos_http_io_initialize方法来初始化网络、内存等全局资源。*/
if (aos_http_io_initialize(NULL, 0) != AOSE_OK) {
exit(1);
/* 用于内存管理的内存池(pool),等价于apr_pool_t。其实现代码在apr库中。*/
aos_pool_t *pool;
/* 重新创建一个内存池,第二个参数是NULL,表示没有继承其它内存池。*/
aos_pool_create(&pool, NULL);
/* 创建并初始化options,该参数包括endpoint、access_key_id、acces_key_secret、is_cname、curl等全局配置信息。*/
oss_request_options_t *oss_client_options;
/* 在内存池中分配内存给options。*/
oss_client_options = oss_request_options_create(pool);
/* 初始化Client的选项oss_client_options。*/
init_options(oss_client_options);
/* 初始化参数。*/
aos_string_t bucket;
aos_string_t object;
aos_table_t *headers = NULL;
aos_table_t *resp_headers = NULL;
aos_status_t *resp_status = NULL;
aos_str_set(&bucket, bucket_name);
aos_str_set(&object, object_name);
headers = aos_table_make(pool, 0);
/* 解冻文件。*/
headers = aos_table_make(pool, 0);
resp_status = oss_restore_object(oss_client_options, &bucket, &object, headers, &resp_headers);
printf("restore object resp_status->code: %d \n", resp_status->code);
if (resp_status->code != 409) {
break;
} else {
printf("restore object is already in progress, resp_status->code: %d \n", resp_status->code);
apr_sleep(5000);
} while (1);
/* 释放内存池,相当于释放了请求过程中各资源分配的内存。*/
aos_pool_destroy(pool);
/* 释放之前分配的全局资源。*/
aos_http_io_deinitialize();
return 0;
}