Object Storage Service (OSS) に保存されているオブジェクトは、キー、データ、およびオブジェクトメタデータで構成されます。 オブジェクトメタデータは、オブジェクトを記述する。 オブジェクトメタデータには、標準HTTPヘッダーとユーザーメタデータが含まれます。 標準のHTTPヘッダーを設定することで、オブジェクトキャッシュポリシーや強制オブジェクトダウンロードポリシーなどのカスタムHTTPリクエストポリシーを作成できます。 ユーザーメタデータを設定して、オブジェクトの目的や属性を識別することもできます。
標準HTTPヘッダー
OSSは、バケットにアップロードされた各オブジェクトの標準HTTPヘッダーを保持します。 次の表に、標準のHTTPヘッダーを示します。
標準HTTPヘッダー | 説明 |
コンテンツタイプ | オブジェクトのメディアタイプ。 ブラウザは、オブジェクトのメディアタイプに基づいて、オブジェクトを読み取るために使用されるフォーマットとエンコードタイプを決定します。 このヘッダーが指定されていない場合、OSSはオブジェクト名の拡張子に基づいて値を割り当てます。 オブジェクト名に拡張子がない場合は、デフォルト値の |
コンテンツエンコーディング | オブジェクトのエンコードに使用されるメソッド。 このヘッダーは、オブジェクトのエンコードタイプに基づいて指定する必要があります。 そうしないと、クライアントとして機能するブラウザがオブジェクトのエンコーディングタイプの解析に失敗するか、オブジェクトのダウンロードに失敗する可能性があります。 オブジェクトがエンコードされていない場合は、このヘッダーを空のままにします。 有効な値:
コンテンツエンコードの詳細については、「RFC 2616」をご参照ください。 重要 オブジェクトにアクセスするときに、HTML、JavaScript、XML、JSONオブジェクトなどの静的webページオブジェクトをGZIPオブジェクトに圧縮する場合は、このヘッダーを空のままにして、 |
コンテンツ言語 | オブジェクトコンテンツの言語。 たとえば、オブジェクトのコンテンツが簡体字中国語で記述されている場合、このヘッダーをzh-CNに設定できます。 |
コンテンツ処理 | オブジェクトの表示に使用されるメソッド。 有効な値:
ブラウザの指定されたダウンロードパスにオブジェクトをダウンロードする場合は、次の項目に注意してください。 説明
オブジェクトURLを使用してオブジェクトにアクセスするときに、オブジェクトを添付ファイルとしてプレビューまたはダウンロードするかどうかは、オブジェクトが保存されているバケットの作成時間、OSSのアクティブ化時間、およびドメイン名の種類によって決まります。 詳細については、「画像オブジェクトが添付ファイルとしてダウンロードされても、そのURLを使用して画像オブジェクトにアクセスしたときにプレビューできない場合はどうすればよいですか?」をご参照ください。 |
キャッシュ制御 | 説明 Cache-Controlが設定されていない場合、OSSはレスポンスヘッダーでこのフィールドを返しません。つまり、Cache-Controlフィールドは存在しません。 この時点で、オブジェクトのキャッシュ動作は、ブラウザ自体のキャッシュポリシーによって決定されます。 オブジェクトのキャッシュ動作。The caching behavior of the object. 有効な値:
|
有効期限 | UTCのキャッシュの有効期限。 例: |
Last-Modified | オブジェクトが最後に変更された時刻。 Last-Modifiedヘッダーは、キャッシュ制御、同期、およびデータ管理のためにOSSによって自動的に更新されます。 このヘッダーの値はUTCにあり、手動で変更することはできません。 詳細については、「OSSオブジェクトのLastModified属性に影響を与える操作は何ですか。 」をご参照ください。 説明 OSSコンソールに表示されるオブジェクトの更新時刻は、UTC時刻から変換されたローカル時刻で、一貫した時刻が表示されます。 たとえば、オブジェクトがUTCで2024された2月28日の13:31:54に最後に更新され、UTC + 8タイムゾーンでオブジェクトをチェックしている場合、OSSコンソールに表示されるオブジェクトの更新時刻は2024年2月28日21:31:54です。 |
コンテンツ長 | オブジェクトのサイズ。 単位はバイトです。 |
ユーザーメタデータ
オブジェクトをアップロードするときに、ユーザーメタデータを追加して、オブジェクトの目的や属性を識別できます。
オブジェクトに複数のユーザーメタデータヘッダーを設定できます。 ただし、オブジェクトのユーザーメタデータの合計サイズは8 KBを超えることはできません。
ユーザーメタデータは、キーと値のペアのセットです。 ユーザーメタデータヘッダーの名前は、
x-oss-meta-
で始まる必要があります。 たとえば、x-oss-meta-last-modified:20210506
は、ローカルファイルが2021年5月6日に最後に変更されたことを示します。GetObject操作またはHeadObject操作を呼び出すと、オブジェクトのユーザーメタデータがHTTPヘッダーとして返されます。
手順
OSSコンソールの使用
OSSコンソールを使用して、一度に最大100個のオブジェクトのオブジェクトメタデータを設定できます。
OSSコンソールにログインします。
左側のナビゲーションウィンドウで、バケットリスト をクリックします。 [バケット] ページで、目的のバケットを見つけてクリックします。
左側のナビゲーションツリーで、ファイル>オブジェクトを選択します。
標準HTTPヘッダーとユーザーメタデータを設定します。
一度に複数のオブジェクトのHTTPヘッダーを設定する
メタデータを設定するオブジェクトを選択し、ファイルメタデータの設定 をクリックします。
単一オブジェクトのHTTPヘッダーの設定
オブジェクトリストでオブジェクトを見つけ、 > ファイルメタデータの設定を選択します。
OKをクリックします。
ossbrowserの使用
ossbrowserを使用して、OSSコンソールで実行できるのと同じオブジェクトレベルの操作を実行できます。 ossbrowserの画面上の指示に従って、オブジェクトメタデータを設定できます。 ossbrowserの使用方法の詳細については、「ossbrowserの使用」をご参照ください。
OSS SDKの使用
次のサンプルコードは、一般的なプログラミング言語でOSS SDKを使用してオブジェクトメタデータを設定する方法の例を示しています。 他のプログラミング言語のOSS SDKを使用してオブジェクトメタデータを設定する方法の詳細については、「概要」をご参照ください。
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.common.utils.BinaryUtil;
import com.aliyun.oss.common.utils.DateUtil;
import com.aliyun.oss.model.ObjectMetadata;
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 bucket name. Example: examplebucket.
String bucketName = "examplebucket";
// Specify the full path of the object. Do not include the bucket name in the full path. Example: testfolder/exampleobject.txt.
String objectName = "testfolder/exampleobject.txt";
String content = "Hello 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 cn-hangzhou.
String region = "cn-hangzhou";
// Create an OSSClient instance.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// Add metadata for the uploaded object.
ObjectMetadata meta = new ObjectMetadata();
String md5 = BinaryUtil.toBase64String(BinaryUtil.calculateMd5(content.getBytes()));
// Enable MD5 verification. After MD5 verification is enabled, OSS calculates the MD5 hash of the uploaded object and compares this MD5 hash with that specified in the request. If the two values are different, an error is reported.
meta.setContentMD5(md5);
// Specify the type of content to upload. The browser determines the format and encoding type that are used to read the object based on the content type of the object. If the content type is not specified, a content type is generated based on the object name extension. If no extension is available, the default value application/octet-stream is used as the content type.
meta.setContentType("text/plain");
// Specify a name for the object when the content is downloaded.
meta.setContentDisposition("attachment; filename=\"DownloadFilename\"");
// Specify the length of the object to upload. If the actual object length is greater than the specified length, the object is truncated. Only the content of the specified length is uploaded. If the actual object length is smaller than the specified length, all content of the object is uploaded.
meta.setContentLength(content.length());
// Specify the caching behavior of the web page when the content is downloaded.
meta.setCacheControl("Download Action");
// Specify the expiration time of the cache in UTC.
meta.setExpirationTime(DateUtil.parseIso8601Date("2022-10-12T00:00:00.000Z"));
// Specify the content encoding format when the content is downloaded.
meta.setContentEncoding("gzip");
// Configure the HTTP headers.
meta.setHeader("yourHeader", "yourHeaderValue");
// Upload the object.
ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(content.getBytes()), meta);
} 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";
// Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt.
$object = "exampledir/exampleobject.txt";
$content = file_get_contents(__FILE__);
$options = array(
OssClient::OSS_HEADERS => array(
'Expires' => '2012-10-01 08:00:00',
'Content-Disposition' => 'attachment; filename="xxxxxx"',
'x-oss-meta-self-define-title' => 'user define meta info',
));
try{
$config = array(
"provider" => $provider,
"endpoint" => $endpoint,
"signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
"region"=> "cn-hangzhou"
);
$ossClient = new OssClient($config);
// Configure object metadata when you upload the object.
$ossClient->putObject($bucket, $object, $content, $options);
} 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: 'examplebucket'
});
async function put() {
try {
let meta = { year: 2016, people: 'mary' };
let result = await client.put('object-name', path.normalize('D:\\localpath\\examplefile.txt'), meta);
console.log(result);
} catch (e) {
console.log(e);
}
}
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.ProviderAuthV4(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 = "https://oss-cn-hangzhou.aliyuncs.com"
# Specify the ID of the region that maps to the endpoint. Example: cn-hangzhou. This parameter is required if you use the signature algorithm V4.
region = "cn-hangzhou"
# Specify the name of your bucket.
bucket = oss2.Bucket(auth, endpoint, "yourBucketName", region=region)
# Specify the full path of the object. Example: exampledir/exampleobject.txt. Do not include the bucket name in the full path.
object_name = 'exampledir/exampleobject.txt'
# Specify the string that you want to upload.
content = '{"age": 1}'
# Configure HTTP headers. For example, set the Content-Type header to 'application/json; charset=utf-8'.
bucket.put_object(object_name, content, headers={'Content-Type': 'application/json; charset=utf-8'})
using Aliyun.OSS;
using Aliyun.OSS.Common;
using Aliyun.OSS.Util;
// 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.
var bucketName = "examplebucket";
// Specify the full path of the object. Do not include the bucket name in the full path.
var objectName = "exampleobject.txt";
// Specify the full path of the local object that you want to upload. By default, if you do not specify the full path of the local object, the local object is uploaded from the path of the project to which the sample program belongs.
var localFilename = "D:\\localpath\\examplefile.txt";
// 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);
c.SetRegion(region);
try
{
using (var fs = File.Open(localFilename, FileMode.Open))
{
// Create metadata for the object. You can configure HTTP headers for the object.
var metadata = new ObjectMetadata()
{
// Specify the content type of the object.
ContentType = "text/html",
// Specify the expiration time of the cache in UTC.
ExpirationTime = DateTime.Parse("2025-10-12T00:00:00.000Z"),
};
// Specify the length of the object content to upload. If the actual object length is greater than the specified length, the object is truncated. Only the content of the specified length is uploaded. If the actual object length is smaller than the specified length, all content of the object is uploaded.
metadata.ContentLength = fs.Length;
// Specify the caching behavior of the web page when the object is downloaded.
metadata.CacheControl = "No-Cache";
// Set mykey1 to myval1.
metadata.UserMetadata.Add("mykey1", "myval1");
// Set mykey2 to myval2.
metadata.UserMetadata.Add("mykey2", "myval2");
var saveAsFilename = "Filetest123.txt";
var contentDisposition = string.Format("attachment;filename*=utf-8''{0}", HttpUtils.EncodeUri(saveAsFilename, "utf-8"));
// Specify a default object name when the required content is saved as an object.
metadata.ContentDisposition = contentDisposition;
// Upload the object and configure object metadata.
client.PutObject(bucketName, objectName, fs, metadata);
Console.WriteLine("Put object succeeded");
// Query object metadata.
var oldMeta = client.GetObjectMetadata(bucketName, objectName);
// Configure new object metadata.
var newMeta = new ObjectMetadata()
{
ContentType = "application/octet-stream",
ExpirationTime = DateTime.Parse("2035-11-11T00:00:00.000Z"),
// Specify the content encoding format of the object when the object is downloaded.
ContentEncoding = null,
CacheControl = ""
};
// Configure user metadata.
newMeta.UserMetadata.Add("author", "oss");
newMeta.UserMetadata.Add("flag", "my-flag");
newMeta.UserMetadata.Add("mykey2", "myval2-modified-value");
// Use the ModifyObjectMeta method to modify the object metadata.
client.ModifyObjectMeta(bucketName, objectName, newMeta);
}
}
catch (Exception ex)
{
Console.WriteLine("Put object failed, {0}", ex.Message);
}
// Create a request to synchronously query object metadata.
// Specify the name of the bucket and the full path of the object. In this example, the bucket name is examplebucket and the full path of the object is exampledir/exampleobject.txt. Do not include the bucket name in the full path of the object.
HeadObjectRequest head = new HeadObjectRequest("examplebucket", "exampledir/exampleobject.txt");
// Query the object metadata.
OSSAsyncTask task = oss.asyncHeadObject(head, new OSSCompletedCallback<HeadObjectRequest, HeadObjectResult>() {
@Override
public void onSuccess(HeadObjectRequest request, HeadObjectResult result) {
// Obtain the length of the object.
Log.d("headObject", "object Size: " + result.getMetadata().getContentLength());
// Query the type of the object.
Log.d("headObject", "object Content Type: " + result.getMetadata().getContentType());
}
@Override
public void onFailure(HeadObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
// Handle request exceptions.
if (clientExcepion != null) {
// Handle client exceptions, such as network exceptions.
clientExcepion.printStackTrace();
}
if (serviceException != null) {
// Handle service exceptions.
Log.e("ErrorCode", serviceException.getErrorCode());
Log.e("RequestId", serviceException.getRequestId());
Log.e("HostId", serviceException.getHostId());
Log.e("RawMessage", serviceException.getRawMessage());
}
}
});
// task.waitUntilFinished(); // Wait until the object metadata is queried.
package main
import (
"log"
"strings"
"time"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
func main() {
// Obtain access credentials from environment variables. Before you run the 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 {
log.Fatalf("Failed to create credentials provider: %v", err)
}
// 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.
// 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.Specify the actual region.
clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
clientOptions = append(clientOptions, oss.Region("yourRegion"))
// Specify the version of the signature algorithm.
clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
client, err := oss.New("yourEndpoint", "", "", clientOptions...)
if err != nil {
log.Fatalf("Failed to create OSS client: %v", err)
}
// Specify the bucket name. Example: examplebucket.
bucketName := "examplebucket" // Replace this parameter with the actual name of your bucket.
bucket, err := client.Bucket(bucketName)
if err != nil {
log.Fatalf("Failed to get bucket: %v", err)
}
// Configure object metadata. Set the expiration time to 23:00:00 January 10, 2049 in GMT, access control list (ACL) to public-read, and MyProp to MyPropVal as user metadata.
expires := time.Date(2049, time.January, 10, 23, 0, 0, 0, time.UTC)
options := []oss.Option{
oss.Expires(expires),
oss.ObjectACL(oss.ACLPublicRead),
oss.Meta("MyProp", "MyPropVal"),
}
// Use a data stream to upload the object.
// Specify the full path of the object. The full path of the object cannot contain the bucket name. Example: exampledir/exampleobject.txt.
objectName := "exampledir/exampleobject.txt" // Replace this parameter with the actual path of the object.
err = bucket.PutObject(objectName, strings.NewReader("MyObjectValue"), options...)
if err != nil {
log.Fatalf("Failed to upload object: %v", err)
}
// Query object metadata.
props, err := bucket.GetObjectDetailedMeta(objectName)
if err != nil {
log.Fatalf("Failed to get object detailed metadata: %v", err)
}
log.Printf("Object Meta: %+v\n", props)
}
OSSHeadObjectRequest * request = [OSSHeadObjectRequest new];
// Specify the bucket name. Example: examplebucket.
request.bucketName = @"examplebucket";
// Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt.
request.objectKey = @"exampledir/exampleobject.txt";
OSSTask * headTask = [client headObject:request];
[headTask continueWithBlock:^id(OSSTask *task) {
if (!task.error) {
NSLog(@"head object success!");
OSSHeadObjectResult * result = task.result;
NSLog(@"header fields: %@", result.httpResponseHeaderFields);
for (NSString * key in result.objectMeta) {
NSLog(@"ObjectMeta: %@ - %@", key, [result.objectMeta objectForKey:key]);
}
} else {
NSLog(@"head object failed, error: %@" ,task.error);
}
return nil;
}];
#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 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. */
std::string Region = "yourRegion";
/* 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;
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);
/* Configure the HTTP headers. */
auto meta = ObjectMetaData();
meta.setContentType("text/plain");
meta.setCacheControl("max-age=3");
/* Configure the user metadata of the object. */
meta.UserMetaData()["meta"] = "meta-value";
std::shared_ptr<std::iostream> content = std::make_shared<std::stringstream>();
*content << "Thank you for using Aliyun Object Storage Service!";
auto outcome = client.PutObject(BucketName, ObjectName, content, meta);
if (!outcome.isSuccess()) {
/* 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;
}
#include "oss_api.h"
#include "aos_http_io.h"
/* 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. */
const char *endpoint = "yourEndpoint";
/* Specify the name of the bucket. Example: examplebucket. */
const char *bucket_name = "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. */
const char *object_name = "exampledir/exampleobject.txt";
const char *object_content= "hello world";
/* 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 char *region = "yourRegion";
void init_options(oss_request_options_t *options)
{
options->config = oss_config_create(options->pool);
/* Use a char* string to initialize aos_string_t. */
aos_str_set(&options->config->endpoint, endpoint);
/* 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. */
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"));
// Specify two additional parameters.
aos_str_set(&options->config->region, region);
options->config->signature_version = 4;
/* Specify whether to use CNAME. The value 0 indicates that CNAME is not used. */
options->config->is_cname = 0;
/* Specify network parameters, such as the timeout period. */
options->ctl = aos_http_controller_create(options->pool, 0);
}
int main(int argc, char *argv[])
{
/* Call the aos_http_io_initialize method in main() to initialize global resources, such as network resources and memory resources. */
if (aos_http_io_initialize(NULL, 0) != AOSE_OK) {
exit(1);
}
/* Create a memory pool to manage memory. aos_pool_t is equivalent to apr_pool_t. The code that is used to create a memory pool is included in the APR library. */
aos_pool_t *pool;
/* Create a memory pool. The value of the second parameter is NULL. This value specifies that the pool does not inherit other memory pools. */
aos_pool_create(&pool, NULL);
/* Create and initialize options. This parameter specifies global configuration information such as endpoint, access_key_id, access_key_secret, is_cname, and curl. */
oss_request_options_t *oss_client_options;
/* Allocate the memory resources in the memory pool to the options. */
oss_client_options = oss_request_options_create(pool);
/* Initialize oss_client_options. */
init_options(oss_client_options);
/* Initialize the parameters. */
aos_string_t bucket;
aos_string_t object;
aos_table_t *headers;
aos_list_t buffer;
aos_table_t *resp_headers = NULL;
aos_status_t *resp_status = NULL;
aos_buf_t *content = NULL;
char *content_length_str = NULL;
char *object_type = NULL;
char *object_author = NULL;
int64_t content_length = 0;
aos_str_set(&bucket, bucket_name);
aos_str_set(&object, object_name);
headers = aos_table_make(pool, 2);
/* Configure user metadata. */
apr_table_set(headers, "Expires", "Fri, 28 Feb 2032 05:38:42 GMT");
apr_table_set(headers, "x-oss-meta-author", "oss");
aos_list_init(&buffer);
content = aos_buf_pack(oss_client_options->pool, object_content, strlen(object_content));
aos_list_add_tail(&content->node, &buffer);
/* Upload an object from the cache. */
resp_status = oss_put_object_from_buffer(oss_client_options, &bucket, &object,
&buffer, headers, &resp_headers);
if (aos_status_is_ok(resp_status)) {
printf("put object from buffer with md5 succeeded\n");
} else {
printf("put object from buffer with md5 failed\n");
}
/* Query object metadata. */
resp_status = oss_get_object_meta(oss_client_options, &bucket, &object, &resp_headers);
if (aos_status_is_ok(resp_status)) {
content_length_str = (char*)apr_table_get(resp_headers, OSS_CONTENT_LENGTH);
if (content_length_str != NULL) {
content_length = atol(content_length_str);
}
object_author = (char*)apr_table_get(resp_headers, OSS_AUTHORIZATION);
object_type = (char*)apr_table_get(resp_headers, OSS_OBJECT_TYPE);
printf("get object meta succeeded, object author:%s, object type:%s, content_length:%ld\n", object_author, object_type, content_length);
} else {
printf("req:%s, get object meta failed\n", resp_status->req_id);
}
/* Release the memory pool. This operation releases memory resources allocated for the request. */
aos_pool_destroy(pool);
/* Release the allocated global resources. */
aos_http_io_deinitialize();
return 0;
}
require 'aliyun/oss'
client = Aliyun::OSS::Client.new(
# 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: 'https://oss-cn-hangzhou.aliyuncs.com',
# Obtain access credentials from environment variables. Before you run the code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
access_key_id: ENV['OSS_ACCESS_KEY_ID'],
access_key_secret: ENV['OSS_ACCESS_KEY_SECRET']
)
# Specify the name of the bucket. Example: examplebucket.
bucket = client.get_bucket('examplebucket')
# Configure object metadata during simple uploads.
bucket.put_object(
'my-object-1',
:file => 'local-file',
:metas => {'year' => '2016', 'people' => 'mary'})
# Configure object metadata during append uploads.
bucket.append_object(
'my-object-2', 0,
:file => 'local-file',
:metas => {'year' => '2016', 'people' => 'mary'})
# Configure object metadata during resumable uploads.
bucket.resumable_upload(
'my-object',
'local-file',
:metas => {'year' => '2016', 'people' => 'mary'})
ossutilの使用
ossutilを使用して、オブジェクトメタデータを設定できます。 詳細については、「set-meta (オブジェクトメタデータの管理) 」をご参照ください。
OSS APIの使用
ビジネスで高度なカスタマイズが必要な場合は、RESTful APIを直接呼び出すことができます。 APIを直接呼び出すには、コードに署名計算を含める必要があります。 詳細は、「PutObject」をご参照ください。