Object metadata includes standard HTTP headers and user metadata. Configure HTTP headers to control caching, content type, and download behavior. Add user metadata to tag objects with custom key-value pairs.
Standard HTTP headers
OSS stores the following standard HTTP headers for each uploaded object.
Standard HTTP header
Description
Content-Type
The media type of the object. Browsers use this header to determine how to read the object. If not specified, OSS assigns a value based on the file extension, or uses the default application/octet-stream. For more information, see How do I configure the Content-Type header?
Content-Encoding
The encoding method applied to the object. Set this header to match the actual encoding. If mismatched, the browser may fail to parse or download the object. Leave empty if the object is not encoded. Valid values:
identity (default): No compression or encoding.
gzip: Encoded with the LZ77 algorithm and 32-bit CRC.
compress: Encoded with the LZW algorithm.
deflate: Encoded with zlib and the deflate algorithm.
If you want static web page objects, such as HTML, JavaScript, XML, and JSON objects, to be compressed into GZIP objects when you access the objects, you must leave this header empty and add the Accept-Encoding: gzip header to your request.
Content-Language
The language of the object content. For example, set this header to zh-CN for simplified Chinese content.
Content-Disposition
Controls whether the browser displays or downloads the object. Valid values:
Content-Disposition:inline: Displays the object in the browser.
Content-Disposition:attachment: Downloads the object with its original name.
Content-Disposition:attachment; filename="yourFileName": Downloads the object with a custom filename.
yourFileName is the custom filename, such as example.jpg.
When downloading objects as attachments, note the following:
Note
If the object name contains special characters such as asterisks (*) or forward slashes (/), the downloaded filename may be escaped. For example, if you download example*.jpg to your local computer, example*.jpg may be escaped as example_.jpg.
To prevent garbled filenames for non-ASCII characters, URL-encode them. For example, to download the Test.txt object with its original name Test.txt, set the Content-Disposition header to attachment;filename=%E6%B5%8B%E8%AF%95.txt;filename*=UTF-8''%E6%B5%8B%E8%AF%95.txt, which derives from "attachment;filename="+URLEncoder.encode("Test","UTF-8")+".txt;filename*=UTF-8''"+URLEncoder.encode("Test","UTF-8")+".txt".
If Cache-Control is not set, OSS omits this field from the response header. The browser then applies its own default caching policy.
Controls caching behavior for the object. Valid values:
no-cache: The cache must revalidate with the origin server before serving.
no-store: No caching of the object.
public: The object can be cached by any cache.
private: The object is cached only on the client.
max-age=<seconds>: The cache validity period in seconds. Available only in HTTP 1.1.
Expires
The expiration time of the cache in UTC. Example: 2022-10-12T00:00:00.000Z. If max-age=<seconds> is included in the Cache-Control header settings, max-age=<seconds> takes precedence over the value of Expires.
The OSS console converts UTC to your local time zone. For example, an object last updated at 13:31:54 UTC on February 28, 2024 is displayed as 21:31:54 in the UTC+8 time zone.
Content-Length
The size of the object. Unit: bytes.
User metadata
Add user metadata when uploading objects to identify their purpose or attributes.
An object supports multiple user metadata headers, up to 8 KB in total.
User metadata headers are key-value pairs. Each header name must start with x-oss-meta-. For example, x-oss-meta-last-modified:20210506 indicates that the local file was last modified on May 6, 2021.
The GetObject and HeadObject operations return user metadata as HTTP headers.
Procedure
Use the OSS console
The OSS console supports configuring metadata for up to 100 objects at a time.
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.
Configure standard HTTP headers and user metadata.
Configure HTTP headers for multiple objects at a time
Select the objects for which you want to configure metadata and click Set Object Metadata.
Configure HTTP headers for a single object
Find the object in the object list and choose > Set Object Metadata.
Click OK.
Use ossbrowser
ossbrowser supports the same object-level operations as the OSS console. For more information, see .
Use OSS SDKs
The following code shows how to configure object metadata with OSS SDKs. For SDKs in other languages, see Overview.
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
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.
// Call the shutdown method to release associated resources when the OSSClient is no longer in use.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// 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; charset=utf-8");
// Configure the headers. For example, specify the storage class for uploaded files.
meta.setHeader("x-oss-storage-class", StorageClass.Standard);
// To enable the following configurations as needed, uncomment the corresponding lines.
// 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");
// 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 path = require('path');
const client = new OSS({
// Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
// Set yourRegion to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to oss-cn-hangzhou.
region: 'oss-cn-hangzhou',
// Use Signature V4.
authorizationV4: true,
// Set yourBucketName to the name of the bucket.
bucket: 'yourBucketName',
// Set yourEndpoint to the Internet endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
endpoint: 'https://oss-cn-hangzhou.aliyuncs.com',
});
async function put() {
try {
// Set metadata as the meta property of the options object.
let result = await client.put('object-name', path.normalize('D:\\localpath\\examplefile.txt'), {
meta: {
year: '2025', // The metadata value must be a string.
people: 'mary'
}
});
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);
client.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.
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 OSS account information. */
/* Set yourEndpoint to the endpoint of the region where the bucket is located. For example, for the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
std::string Endpoint = "yourEndpoint";
/* Set yourRegion to the region where the bucket is located. For example, for the China (Hangzhou) region, set the region to cn-hangzhou. */
std::string Region = "yourRegion";
/* Specify the bucket name. Example: examplebucket. */
std::string BucketName = "examplebucket";
/* Specify the full path of the object. The full path cannot contain the bucket name. Example: exampledir/exampleobject.txt. */
std::string ObjectName = "exampledir/exampleobject.txt";
/* Initialize network resources. */
InitializeSdk();
ClientConfiguration conf;
conf.signatureVersion = SignatureVersionType::V4;
/* Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. */
auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
OssClient client(Endpoint, credentialsProvider, conf);
client.SetRegion(Region);
/* Set HTTP headers. */
auto meta = ObjectMetaData();
meta.setContentType("text/plain");
meta.setCacheControl("max-age=3");
/* Set custom object metadata. */
meta.UserMetaData()["meta"] = "meta-value";
std::shared_ptr<std::iostream> content = std::make_shared<std::stringstream>();
*content << "Thank you for using Alibaba Cloud 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 network resources. */
ShutdownSdk();
return 0;
}
#include "oss_api.h"
#include "aos_http_io.h"
/* Set yourEndpoint to the Endpoint of the region where the bucket is located. For example, for the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
const char *endpoint = "yourEndpoint";
/* Specify the bucket name. For example, examplebucket. */
const char *bucket_name = "examplebucket";
/* Specify the full path of the object. The full path cannot contain the bucket name. For example, exampledir/exampleobject.txt. */
const char *object_name = "exampledir/exampleobject.txt";
const char *object_content= "hello world";
/* Set yourRegion to the region where the bucket is located. For example, for 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);
/* Initialize an aos_string_t type with a char* string. */
aos_str_set(&options->config->endpoint, endpoint);
/* Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. */
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"));
// Configure the following two additional parameters.
aos_str_set(&options->config->region, region);
options->config->signature_version = 4;
/* Specify whether a CNAME is used. A value of 0 indicates that no CNAME is used. */
options->config->is_cname = 0;
/* Set 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 at the program entry to initialize global resources such as the network and memory. */
if (aos_http_io_initialize(NULL, 0) != AOSE_OK) {
exit(1);
}
/* The memory pool for memory management is equivalent to apr_pool_t. The implementation code is in the apr library. */
aos_pool_t *pool;
/* Create a new memory pool. The second parameter is NULL, which indicates that the new pool does not inherit from another memory pool. */
aos_pool_create(&pool, NULL);
/* Create and initialize options. This parameter contains global configuration information, such as endpoint, access_key_id, access_key_secret, is_cname, and curl. */
oss_request_options_t *oss_client_options;
/* Allocate memory for options in the memory pool. */
oss_client_options = oss_request_options_create(pool);
/* Initialize the client options oss_client_options. */
init_options(oss_client_options);
/* Initialize 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);
/* Set user-defined 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 the object from the buffer. */
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");
}
/* Get the 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 releases the memory allocated to resources during the request. */
aos_pool_destroy(pool);
/* Release the previously allocated global resources. */
aos_http_io_deinitialize();
return 0;
}
require 'aliyun/oss'
client = Aliyun::OSS::Client.new(
# Specify the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
endpoint: 'https://oss-cn-hangzhou.aliyuncs.com',
# Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
access_key_id: ENV['OSS_ACCESS_KEY_ID'],
access_key_secret: ENV['OSS_ACCESS_KEY_SECRET']
)
# Specify the bucket name. Example: examplebucket.
bucket = client.get_bucket('examplebucket')
# Set object metadata during a simple upload.
bucket.put_object(
'my-object-1',
:file => 'local-file',
:metas => {'year' => '2016', 'people' => 'mary'})
# Set object metadata during an append upload.
bucket.append_object(
'my-object-2', 0,
:file => 'local-file',
:metas => {'year' => '2016', 'people' => 'mary'})
# Set object metadata during a resumable upload.
bucket.resumable_upload(
'my-object',
'local-file',
:metas => {'year' => '2016', 'people' => 'mary'})
package main
import (
"context"
"flag"
"log"
"strings"
"time"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)
// Define global variables.
var (
region string // The storage region.
bucketName string // The bucket name.
objectName string // The object name.
)
// The init function is used to initialize command-line parameters.
func init() {
flag.StringVar(®ion, "region", "", "The region in which the bucket is located.")
flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
flag.StringVar(&objectName, "object", "", "The name of the object.")
}
func main() {
// Parse command-line parameters.
flag.Parse()
// Check whether the bucket name is empty.
if len(bucketName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, bucket name required")
}
// Check whether the region is empty.
if len(region) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, region required")
}
// Check whether the object name is empty.
if len(objectName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, object name required")
}
// Define the content to upload.
content := "hi oss"
// Load the default configurations and set the credential provider and region.
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion(region)
// Create an OSS client.
client := oss.NewClient(cfg)
// Create a request to upload an object.
request := &oss.PutObjectRequest{
Bucket: oss.Ptr(bucketName), // The bucket name.
Key: oss.Ptr(objectName), // The object name.
Body: strings.NewReader(content), // The content to upload.
Expires: oss.Ptr(time.Date(2038, 12, 31, 12, 0, 0, 0, time.UTC).Format(time.RFC1123)), // The expiration time of the object.
Acl: oss.ObjectACLPublicRead,
Metadata: map[string]string{ // Custom metadata.
"Author": "alibaba oss sdk", // The author of the object.
"Date": "2024-07-01", // The creation date of the object.
},
}
// Send the request to upload the object.
result, err := client.PutObject(context.TODO(), request)
if err != nil {
log.Fatalf("failed to put object %v", err)
}
// Print the result of the object upload.
log.Printf("put object result:%#v\n", result)
}