Esta página ainda não está disponível no idioma selecionado. Estamos trabalhando para adicionar mais opções de idiomas. Agradecemos sua compreensão.

Compute
Elastic Cloud Server
Huawei Cloud Flexus
Bare Metal Server
Auto Scaling
Image Management Service
Dedicated Host
FunctionGraph
Cloud Phone Host
Huawei Cloud EulerOS
Networking
Virtual Private Cloud
Elastic IP
Elastic Load Balance
NAT Gateway
Direct Connect
Virtual Private Network
VPC Endpoint
Cloud Connect
Enterprise Router
Enterprise Switch
Global Accelerator
Management & Governance
Cloud Eye
Identity and Access Management
Cloud Trace Service
Resource Formation Service
Tag Management Service
Log Tank Service
Config
OneAccess
Resource Access Manager
Simple Message Notification
Application Performance Management
Application Operations Management
Organizations
Optimization Advisor
IAM Identity Center
Cloud Operations Center
Resource Governance Center
Migration
Server Migration Service
Object Storage Migration Service
Cloud Data Migration
Migration Center
Cloud Ecosystem
KooGallery
Partner Center
User Support
My Account
Billing Center
Cost Center
Resource Center
Enterprise Management
Service Tickets
HUAWEI CLOUD (International) FAQs
ICP Filing
Support Plans
My Credentials
Customer Operation Capabilities
Partner Support Plans
Professional Services
Analytics
MapReduce Service
Data Lake Insight
CloudTable Service
Cloud Search Service
Data Lake Visualization
Data Ingestion Service
GaussDB(DWS)
DataArts Studio
Data Lake Factory
DataArts Lake Formation
IoT
IoT Device Access
Developer Tools
SDK Developer Guide
API Request Signing Guide
Terraform
Koo Command Line Interface
Content Delivery & Edge Computing
Content Delivery Network
Intelligent EdgeFabric
CloudPond
Intelligent EdgeCloud
Solutions
SAP Cloud
High Performance Computing
Media Services
Media Processing Center
Video On Demand
Live
SparkRTC
MetaStudio
Developer Services
ServiceStage
CodeArts
CodeArts PerfTest
CodeArts Req
CodeArts Pipeline
CodeArts Build
CodeArts Deploy
CodeArts Artifact
CodeArts TestPlan
CodeArts Check
CodeArts Repo
Cloud Application Engine
Huawei Cloud Astro Canvas
Huawei Cloud Astro Zero
CodeArts Governance
Storage
Object Storage Service
Elastic Volume Service
Cloud Backup and Recovery
Storage Disaster Recovery Service
Scalable File Service Turbo
Scalable File Service
Volume Backup Service
Cloud Server Backup Service
Data Express Service
Dedicated Distributed Storage Service
Containers
Cloud Container Engine
SoftWare Repository for Container
Application Service Mesh
Ubiquitous Cloud Native Service
Cloud Container Instance (CCI)
Databases
Relational Database Service
Document Database Service
Data Admin Service
Data Replication Service
GeminiDB
GaussDB
Distributed Database Middleware
Database and Application Migration UGO
TaurusDB
Middleware
Distributed Cache Service
API Gateway
Distributed Message Service for Kafka
Distributed Message Service for RabbitMQ
Distributed Message Service for RocketMQ
Cloud Service Engine
Multi-Site High Availability Service
EventGrid
Dedicated Cloud
Dedicated Computing Cluster
Business Applications
Workspace
ROMA Connect
Message & SMS
Domain Name Service
Edge Data Center Management
Meeting
AI
Face Recognition Service
Graph Engine Service
Content Moderation
Image Recognition
Optical Character Recognition
ModelArts
ImageSearch
Conversational Bot Service
Speech Interaction Service
Huawei HiLens
Video Intelligent Analysis Service
Cloud Transformation
Well-Architected Framework
Cloud Adoption Framework
Others
Product Pricing Details
System Permissions
Console Quick Start
Common FAQs
Instructions for Associating with a HUAWEI CLOUD Partner
Message Center
Security & Compliance
Security Technologies and Applications
Web Application Firewall
Host Security Service
Cloud Firewall
SecMaster
Anti-DDoS Service
Data Encryption Workshop
Database Security Service
Cloud Bastion Host
Data Security Center
Cloud Certificate Manager
Edge Security
Blockchain
Blockchain Service
Web3 Node Engine Service
MacroVerse aPaaS
KooMessage
KooPhone
KooDrive

Setting Object Properties (SDK for C)

Updated on 2025-05-16 GMT+08:00
NOTICE:

If you have any questions during development, post them on the Issues page of GitHub.

Function

This API sets properties for an object when uploading it. Object properties include the object length, MIME type, MD5 value (for verification), storage class, and custom object metadata. You can configure properties for an object that is being uploaded in streaming, file-based, or multipart mode or when copying an object.

Restrictions

  • The mapping between OBS regions and endpoints must comply with what is listed in Regions and Endpoints.
  • An object can have multiple pieces of metadata. The size of the metadata cannot exceed 8 KB in total.
  • Currently, metadata names only support ASCII characters. Non-ASCII characters must be Base64-encoded.
  • If you do not set a storage class for an object, the object will inherit the storage class of its bucket by default.

Method

void set_object_metadata(const obs_options *options, obs_object_info *object_info, 
	obs_put_properties *put_properties,
	server_side_encryption_params *encryption_params,
	obs_response_handler *handler, void *callback_data);

Request Parameters

Table 1 List of request parameters

Parameter

Type

Mandatory (Yes/No)

Description

options

const obs_options*

Yes

Explanation:

The context of the requested bucket. Refer to Configuring option (SDK for C) to set the AK, SK, endpoint, bucket, timeout, and temporary credentials through obs_options.

Restrictions:

None

object_info

obs_object_info *

Yes

Explanation:

Object name and version ID.

Restrictions:

For a non-versioned object, set the version ID to 0.

put_properties

obs_put_properties*

Yes

Explanation:

Properties of the uploaded object

Restrictions:

None

encryption_params

server_side_encryption_params *

No

Explanation:

Encryption setting of the uploaded object

Restrictions:

None

handler

obs_response_handler *

Yes

Explanation:

A callback structure where all members are pointers to callback functions, used to set the callback functions that handle response data. You can set a callback function to copy the response data from the server to your custom callback_data.

Restrictions:

None

callback_data

void *

No

Explanation:

Custom callback data.

Restrictions:

None

Value range:

None

Default value:

None

Table 2 obs_options

Parameter

Type

Mandatory (Yes/No)

Description

bucket_options

obs_bucket_context

Yes

Explanation:

Bucket settings.

Restrictions:

None

request_options

obs_http_request_option

Yes

Explanation:

Request-related settings.

Restrictions:

None

temp_auth

temp_auth_configure*

No

Explanation:

The structure used to calculate a temporary signature. Set it to NULL if it is not used.

Restrictions:

None

Table 3 obs_bucket_context

Parameter

Type

Mandatory (Yes/No)

Description

host_name

char *

Yes

Explanation:

The requested host name, used as an address for connecting to OBS. It is the domain name (the endpoint) of the server where the requested resource is stored.

Example: host_name = "obs.ap-southeast-1.myhuaweicloud.com";

Restrictions:

The value does not need to contain http:// or https:// as a prefix, which is controlled using obs_protocol.

Value range:

To view the endpoints available for OBS, see Regions and Endpoints.

Default value:

None

bucket_name

char *

Yes

Explanation:

Bucket name.

Restrictions:

  • A bucket name must be unique across all accounts and regions.
  • A bucket name:
    • Must be 3 to 63 characters long and start with a digit or letter. Lowercase letters, digits, hyphens (-), and periods (.) are allowed.
    • Cannot be formatted as an IP address.
    • Cannot start or end with a hyphen (-) or period (.).
    • Cannot contain two consecutive periods (..), for example, my..bucket.
    • Cannot contain a period (.) and a hyphen (-) adjacent to each other, for example, my-.bucket or my.-bucket.
  • If you repeatedly create buckets with the same name in the same region, no error will be reported and the bucket properties comply with those set in the first creation request.

Value range:

None

Default value:

None

useCname

bool

No

Explanation:

Whether to use a custom domain name to access OBS.

Restrictions:

None

Value range:

true: A custom domain name is used.

false: A custom domain name is not used.

Default value:

false

protocol

obs_protocol

No

Explanation:

Whether to use the HTTP or HTTPS protocol.

Restrictions:

None

Value range:

For details, see obs_protocol.

Default value:

OBS_PROTOCOL_HTTPS (HTTPS is used by default.)

access_key

char *

Yes

Explanation:

Access key ID (AK).

Restrictions:

None

Value range:

For details, see Creating Access Keys.

Default value:

None

secret_access_key

char *

Yes

Explanation:

Secret access key (SK).

Restrictions:

For details, see Creating Access Keys.

Value range:

None

Default value:

None

storage_class

obs_storage_class

No

Explanation:

Bucket storage class that can be specified at bucket creation.

Restrictions:

None

Value range:

For details, see obs_storage_class.

Default value:

OBS_STORAGE_CLASS_STANDARD (Standard storage class)

token

char *

No

Explanation:

The security token in temporary credentials.

Restrictions:

None

Value range:

For details, see Creating Access Keys.

Default value:

None

epid

char *

No

Explanation:

Enterprise project ID that can be specified during bucket creation. If you have enabled EPS, you can obtain the project ID from the EPS console.

Restrictions:

The value needs to be represented as a UUID. This parameter is not required if EPS is not enabled.

Example: 9892d768-2d13-450f-aac7-ed0e44c2585f

Default value:

None

bucket_type

obs_bucket_type

No

Explanation:

Whether a bucket is an object bucket or a parallel file system.

Restrictions:

None

Value range:

For details, see obs_bucket_type.

Default value:

OBS_BUCKET_OBJECT (object bucket)

bucket_list_type

obs_bucket_list_type

No

Explanation:

Whether to list all buckets, object buckets, or parallel file systems.

Restrictions:

None

Value range:

For details, see obs_bucket_list_type.

Table 4 obs_storage_class

Value

Description

OBS_STORAGE_CLASS_STANDARD

Standard storage class.

This class features low access latency and high throughput and is used for storing massive, frequently accessed (multiple times a month) or small objects (< 1 MB) requiring quick response.

OBS_STORAGE_CLASS_STANDARD_IA

Infrequent Access storage class.

Used for storing data that is semi-frequently accessed (fewer than 12 times a year) but becomes instantly available when needed.

OBS_STORAGE_CLASS_GLACIER

Archive storage class.

Used for storing rarely accessed (once a year) data.

Table 5 obs_http_request_option

Parameter

Type

Mandatory (Yes/No)

Description

connect_time

int

Yes

Explanation:

Timeout period for establishing an HTTP/HTTPS connection, in ms.

Restrictions:

None

Value range:

[10000, 60000]

Default value:

60000

max_connected_time

int

Yes

Explanation:

Timeout period (in seconds) of a request.

Restrictions:

None

Value range:

None

Default value:

0 (There is never automatic disconnection.)

proxy_auth

char*

No

Explanation:

Proxy authentication information, in the format username:password

Restrictions:

None

Value range:

None

Default value:

None

proxy_host

char*

No

Explanation:

IP address or host name of the proxy server.

Restrictions:

None

Value range:

None

Default value:

None

Table 6 obs_protocol

Value

Description

OBS_PROTOCOL_HTTPS

HTTPS is used for access.

OBS_PROTOCOL_HTTP

HTTP is used for access.

Table 7 obs_bucket_type

Value

Description

OBS_BUCKET_OBJECT

Object bucket

OBS_BUCKET_PFS

Parallel file system

Table 8 obs_bucket_list_type

Value

Description

OBS_BUCKET_LIST_ALL

Lists all buckets.

OBS_BUCKET_LIST_OBJECT

Lists all object buckets.

OBS_BUCKET_LIST_PFS

Lists all parallel file systems.

Table 9 temp_auth_configure

Parameter

Type

Mandatory (Yes/No)

Description

expires

long long int

Yes

Explanation:

Validity period of the temporary credentials, in seconds.

Restrictions:

None

Value range:

[0-630720000]

Default value:

None

temp_auth_callback

void(*temp_auth_callback)(char *temp_auth_url,

uint64_t temp_auth_url_len,

char*temp_auth_headers,

uint64_t temp_auth_headers_len,

void*callback_data)

Yes

Explanation:

The pointer to the custom callback function, which is used to record the temporary URL and involved signature header to the custom callback data.

Restrictions:

None

callback_data

void *

Yes

Explanation:

Custom callback data.

Restrictions:

None

Value range:

None

Default value:

None

Table 10 temp_auth_callback

Parameter

Type

Mandatory (Yes/No)

Description

temp_auth_url

char *

Yes

Explanation:

Temporary URL. OBS allows you to construct a URL for a specific operation. In such a URL, you use Query parameters to provide authentication information including the user AK, signature, and validity period. Anyone who has the URL can perform the specified operation. After receiving a request made using such a URL, OBS treats the requester as the user who issued the URL and processes the request. For example, if you construct a pre-signed URL for downloading an object and provide it to various users, they can use the URL to download the object without authentication, but they must do so within the validity period specified by the Expires parameter.

Restrictions:

None

Value range:

None

Default value:

None

temp_auth_url_len

uint64_t

Yes

Explanation:

Length of the temporary URL.

Restrictions:

None

Value range:

None

Default value:

None

temp_auth_headers

char *

Yes

Explanation:

Headers for temporary authentication.

Restrictions:

None

Value range:

None

Default value:

None

temp_auth_headers_len

uint64_t

Yes

Explanation:

Number of temporary authentication headers.

Restrictions:

None

Value range:

None

Default value:

None

callback_data

void *

Yes

Explanation:

Custom callback data.

Restrictions:

None

Value range:

None

Default value:

None

Table 11 obs_object_info

Parameter

Type

Mandatory (Yes/No)

Description

key

char *

Yes

Explanation:

Object name

Restrictions:

None

Value range:

None

Default value:

None

version_id

char *

No

Explanation:

Object version ID. If the object is not a versioned object, set version_id to NULL.

Restrictions:

None

Value range:

None

Default value:

None

Table 12 obs_put_properties

Parameter

Type

Mandatory (Yes/No)

Description

content_type

char *

Yes

Explanation:

It specifies the file type of an object when it is downloaded.

Restrictions:

None

Value range:

See the Content-Type values defined in HTTP.

Default value:

None

md5

char *

Yes

Explanation:

Indicates the base64-encoded digest of the object data. It is provided for the OBS server to verify data integrity. The OBS server will compare this MD5 value with the MD5 value calculated based on the object data. If the two values are not the same, HTTP status code 400 is returned.

Restrictions:

The MD5 value of the object must be Base64 encoded. If the MD5 value is not specified, the OBS server will not verify the MD5 value of the object.

Value range:

Base64-encoded 128-bit MD5 value of the request body calculated according to RFC 1864.

Example: n58IG6hfM7vqI4K0vnWpog==

Default value:

None

cache_control

char *

Yes

Explanation:

It specifies the cache behavior of the web page when an object is downloaded.

Restrictions:

None

Value range:

See the Cache-Control values defined in HTTP.

Default value:

None

content_disposition_filename

char *

Yes

Explanation:

It specifies the name of an object when it is downloaded. For example, if the value is set to test.txt, that is equivalent to adding the Content-Disposition: attachment; filename=test.txt header.

Restrictions:

None

Value range:

See the Content-Disposition values defined in HTTP.

Default value:

None

content_encoding

char *

Yes

Explanation:

It specifies the content encoding format when an object is downloaded.

Restrictions:

None

Value range:

See the Content-Encoding values defined in HTTP.

Default value:

None

website_redirect_location

char *

Yes

Explanation:

If the bucket is configured with website hosting, the request for obtaining the object can be redirected to another object in the bucket or an external URL.

To another object in the same bucket:

x-obs-website-redirect-location:/anotherPage.html

To an external URL:

x-obs-website-redirect-location:http://www.example.com/

Restrictions:

The value must start with a slash (/), http://, or https:// and cannot exceed 2 KB.

Value range:

None

Default value:

None

get_conditions

obs_get_conditions *

No

Explanation:

Specifies a series of parameters for copying an object.

Restrictions:

None

start_byte

uint64_t

No

Explanation:

Where the copy starts in the object

Restrictions:

None

Value range:

0 (included) to the object length minus 1 (not included), in bytes

Default value:

0 (The copy starts from the first byte of the object.)

byte_count

uint64_t

No

Explanation:

Specifies the copy length.

Restrictions:

  • Value: an integer greater than 0
  • If the sum of start_byte and byte_count is greater than the object length minus 1, the object length minus 1 is used. The unit is byte.

Value range:

None

Default value:

None

upload_limit

uint64_t

No

Explanation:

Bandwidth limit for single connection requests.

Restrictions:

None

Value range:

819200 to 838860800, in bit/s

Default value:

None

expires

int64_t

No

Explanation:

Value of the Expires header in the OBS request. It specifies the cache expiration time of the web page when the object is downloaded.

Restrictions:

None

Value range:

None

Default value:

None

obs_expires

int64_t

No

Explanation:

Specifies when an object expires. It is measured in days. Once the object expires, it is automatically deleted.

Restrictions:

The value must be greater than the number of days that have passed since the object was created. For example, if the object was uploaded 10 days ago, you must specify a value greater than 10.

Value range:

The value is an integer greater than 0.

Default value:

None

canned_acl

obs_canned_acl

No

Explanation:

Access control policy

Restrictions:

None

Value range:

For details, see obs_canned_acl.

az_redundancy

obs_az_redundancy

No

Explanation:

Specifies a series of parameters for copying an object.

Restrictions:

None

Value range:

For details, see obs_az_redundancy.

meta_data_count

int

No

Explanation:

Number of elements in the meta_data array.

Restrictions:

None

Value range:

None

Default value:

None

meta_data

obs_name_value*

No

Explanation:

Custom metadata of the object. OBS allows you to use custom metadata to manage objects. When you retrieve or query the metadata of the object, the added custom metadata headers will be returned in the response.

Restrictions:

  • If a request carries this header field, the response message must contain this header field.
  • The total size of all custom metadata cannot exceed 8 KB. To measure the size, calculate the sum of bytes of all UTF-8 encoded keys and values.
  • The custom metadata keys are case-insensitive, but are stored in lowercase by OBS. The key values are case-sensitive.
  • Both custom metadata keys and their values must conform to US-ASCII standards. If non-ASCII or unrecognizable characters are required, they must be encoded and decoded in URL or Base64 on the client, because the server does not perform such operations.

metadata_action

metadata_action_indicator

No

Explanation:

Metadata operation directive.

Restrictions:

None

Value range:

For details, see metadata_action_indicator.

server_callback

obs_upload_file_server_callback

No

Explanation:

Parameters related to server callback.

Restrictions:

None

Table 13 obs_canned_acl

Value

Description

OBS_CANNED_ACL_PRIVATE

Private read and write. A bucket or object can only be accessed by its owner.

OBS_CANNED_ACL_PUBLIC_READ

Public read and private write. If this permission is granted on a bucket, anyone can read the object list, multipart tasks, metadata, and object versions in the bucket.

If this permission is set for an object, everyone can obtain the content and metadata of the object.

OBS_CANNED_ACL_PUBLIC_READ_WRITE

Public read and write. If this permission is set for a bucket, everyone can obtain the object list in the bucket, multipart uploads in the bucket, metadata of the bucket; upload objects; delete objects; initialize multipart uploads; upload parts; combine parts; copy parts; and abort multipart uploads.

If this permission is set for an object, everyone can obtain the content and metadata of the object.

OBS_CANNED_ACL_PUBLIC_READ_DELIVERED

Public read on a bucket and its objects. If this permission is granted on a bucket, anyone can read the object list, multipart tasks, and bucket metadata, and can also read the content and metadata of the objects in the bucket.

This permission cannot be granted on objects.

OBS_CANNED_ACL_PUBLIC_READ_WRITE_DELIVERED

Public read and write on a bucket and its objects. If this permission is granted on a bucket, anyone can read the object list, multipart uploads, and bucket metadata, and can upload or delete objects, initiate multipart upload tasks, upload parts, assemble parts, copy parts, and abort multipart uploads. They can also read the content and metadata of the objects in the bucket.

This permission cannot be granted on objects.

OBS_CANNED_ACL_BUCKET_OWNER_FULL_CONTROL

If this permission is granted on an object, only the bucket and object owners have the full control over the object.

By default, if you upload an object to a bucket of any other user, the bucket owner does not have the permissions on your object. After you grant this permission to the bucket owner, the bucket owner can have full control over your object.

For example, if user A uploads object x to user B's bucket, user B does not have the control over object x. If user A sets bucket-owner-full-control for object x, user B then has the control over object x.

Table 14 obs_get_conditions

Parameter

Type

Mandatory (Yes/No)

Description

start_byte

uint64_t

No

Explanation:

Start position for object download.

Restrictions:

None

Value range:

0 (included) to the object length minus 1 (not included), in bytes

Default value:

0 (indicating that the download starts from the first byte of the object)

byte_count

uint64_t

No

Explanation:

Specifies the length to be downloaded.

Restrictions:

  • Value: an integer greater than 0
  • If the sum of start_byte and byte_count is greater than the object length minus 1, the object length minus 1 is used. The unit is byte.

Value range:

None

Default value:

None

download_limit

uint64_t

No

Explanation:

Bandwidth limit for single connection requests.

Restrictions:

None

Value range:

819200 to 838860800, in bit/s

Default value:

None

if_modified_since

int64_t

No

Explanation:

The request succeeds if the object has been modified since the specified time; otherwise, an error is returned.

Restrictions:

None

Value range:

None

Default value:

None

if_not_modified_since

int64_t

No

Explanation:

The request succeeds if the object has not been modified since the specified time; otherwise, an error is returned.

Restrictions:

None

Value range:

None

Default value:

None

if_match_etag

char *

No

Explanation:

Preset ETag. If the ETag of the object to be downloaded or copied is the same as the preset ETag, the request succeeds. Otherwise, an error is returned.

Restrictions:

None

Value range:

The value must contain 32 characters.

Default value:

None

if_not_match_etag

char *

No

Explanation:

Preset ETag. If the ETag of the object to be downloaded or copied is different from the preset ETag, the request succeeds. Otherwise, an error is returned.

Restrictions:

None

Value range:

The value must contain 32 characters.

Default value:

None

image_process_config

image_process_configure *

No

Explanation:

Image processing parameters.

Restrictions:

None

Table 15 metadata_action_indicator

Value

Description

OBS_NO_METADATA_ACTION

Default invalid value.

OBS_REPLACE

Uses the complete header carried in the current request to replace the original one and deletes the metadata that is not specified.

OBS_REPLACE_NEW

The metadata that has an existing value is replaced. A value is assigned to the metadata that does not have a value. The metadata that is not specified remains unchanged. Custom metadata is replaced.

Table 16 obs_upload_file_server_callback

Parameter

Type

Mandatory (Yes/No)

Description

callback_url

char *

Yes

Explanation:

After an object is uploaded successfully, OBS sends a callback request to the URL using the POST method.

You can specify a maximum of 10 URLs. Use semicolons (;) to separate URLs.

URL-encoding is required.

Restrictions:

None

Value range:

None

Default value:

None

callback_host

char *

No

Explanation:

Value of the host header in the callback request. If this parameter is not specified, the value of host parsed from the callbackUrl parameter is used.

Restrictions:

None

Value range:

None

Default value:

None

callback_body_type

char *

No

Explanation:

Value of the Content-Type header in the callback request. application/x-www-form-urlencoded and application/json are supported. If this parameter is not specified, the default value is as follows:

application/json

Restrictions:

None

Value range:

None

Default value:

None

Table 17 image_process_configure

Parameter

Type

Mandatory (Yes/No)

Description

image_process_mode

image_process_mode_type

No

Explanation:

Image processing parameters.

Restrictions:

None

Value range:

For details, see image_process_mode_type.

cmds_stylename

char *

No

Explanation:

Image processing parameters.

Restrictions:

None

Value range:

None

Default value:

None

Table 18 image_process_mode_type

Value

Description

obs_image_process_invalid_mode

Default invalid value.

obs_image_process_cmd

Image processing parameters start with image.

obs_image_process_style

Image processing parameters start with style.

Table 19 server_side_encryption_params

Parameter

Type

Mandatory (Yes/No)

Description

encryption_type

obs_encryption_type

No

Explanation:

Encryption type.

Restrictions:

None

Value range:

For details, see obs_encryption_type.

kms_server_side_encryption

char *

No

Explanation:

Indicates that SSE-KMS is used for server-side encryption.

Restrictions:

None

Value range:

  • kms
  • AES256

Default value:

None

kms_key_id

char *

No

Explanation:

Key ID. If the SSE-KMS encryption is used with a specified key, the key ID is required.

Restrictions:

This header can only be used when you specify kms for the kms_server_side_encryption header.

Value range:

None

Default value:

If you specify kms for encryption but do not specify a key ID, the default master key will be used. If there is not a default master key, OBS will create one and use it.

ssec_customer_algorithm

char *

No

Explanation:

Indicates the algorithm used to encrypt an object.

Restrictions:

The header is used only in SSE-C mode.

Value range:

AES256 (AES256 encryption algorithm)

Default value:

None

ssec_customer_key

char *

No

Explanation:

Indicates the key used to encrypt an object.

Restrictions:

The header is used only in SSE-C mode.

Value range:

Base64-encoded 256-bit key

Default value:

None

des_ssec_customer_algorithm

char *

No

Explanation:

Indicates the algorithm used to decrypt a source object.

Restrictions:

The header is used only in SSE-C mode.

Value range:

None

Default value:

None

des_ssec_customer_key

char *

No

Explanation:

Indicates the key used to decrypt the source object.

Restrictions:

The header is used only in SSE-C mode.

Value range:

None

Default value:

None

Table 20 obs_encryption_type

Value

Description

OBS_ENCRYPTION_KMS

Use the KMS encryption.

OBS_ENCRYPTION_SSEC

Use the SSE-C encryption.

Table 21 obs_response_handler

Parameter

Type

Mandatory (Yes/No)

Description

properties_callback

obs_response_properties_callback *

Yes

Explanation:

The pointer to the response callback function. The content of properties in the callback can be recorded in callback_data (custom callback data).

Restrictions:

None

complete_callback

obs_response_complete_callback *

Yes

Explanation:

The pointer to the completion callback function. The content of obs_status and obs_error_details in the callback can be recorded in callback_data (custom callback data).

Restrictions:

None

Table 22 obs_response_properties_callback

Parameter

Type

Mandatory (Yes/No)

Description

properties

const obs_response_properties*

Yes

Explanation:

Parameters in the response headers. You are advised to record them to callback_data (custom callback data).

Restrictions:

None

callback_data

void *

Yes

Explanation:

The pointer to the custom callback data.

Restrictions:

None

Value range:

None

Default value:

None

Table 23 obs_response_complete_callback

Parameter

Type

Mandatory (Yes/No)

Description

status

obs_status

Yes

Explanation:

Internal request status code of the SDK.

Restrictions:

None

Value range:

For details, see obs_status.

error_details

const obs_error_details*

Yes

Explanation:

The pointer to the response callback function. The content of properties in the callback can be recorded in callback_data (custom callback data).

Restrictions:

None

callback_data

void *

Yes

Explanation:

The pointer to the custom callback data.

Restrictions:

None

Value range:

None

Default value:

None

Table 24 obs_response_properties

Parameter

Type

Mandatory (Yes/No)

Description

request_id

const char *

No

Explanation:

The value created by OBS to uniquely identify the request. OBS uses this value to locate the fault.

Restrictions:

None

Value range:

None

Default value:

None

request_id2

const char *

No

Explanation:

A special symbol that helps troubleshoot.

Restrictions:

None

Value range:

None

Default value:

None

content_type

const char *

No

Explanation:

MIME type of the object. MIME type is a standard way of describing a data type and is used by the browser to decide how to display data.

Restrictions:

None

Value range:

None

Default value:

None

content_length

uint64_t

No

Explanation:

The size (in bytes) of the response body.

Restrictions:

None

Value range:

None

Default value:

None

server

const char *

No

Explanation:

Server header in an HTTP request.

Restrictions:

None

Value range:

None

Default value:

None

etag

const char *

No

Explanation:

Base64-encoded, 128-bit MD5 value of an object. It uniquely identifies the content of an object and can be used to check the object integrity. For example, if the ETag is A when an object is uploaded and is B when the object is downloaded, it indicates that the object content has been changed. The ETag reflects changes to the contents of the object, not its metadata. An object created by an upload or copy operation has a unique ETag.

Restrictions:

If an object is encrypted using server-side encryption, the ETag is not the MD5 value of the object.

Value range:

The value must contain 32 characters.

Default value:

None

expiration

const char *

No

Explanation:

Expiration details of the object.

Restrictions:

None

Value range:

An integer greater than 0, in days.

Default value:

None

website_redirect_location

const char *

No

Explanation:

Indicates where an object request is redirected. If the bucket that contains the object is configured with Website settings, this parameter can be set in the object metadata so that the request for the object can be redirected to another object in the same bucket or an external URL after the website returns a 301 redirect response.

To another object in the same bucket:

x-obs-website-redirect-location:/anotherPage.html

To an external URL:

x-obs-website-redirect-location:http://www.example.com/

OBS obtains the specified value from the header and stores it in the object metadata WebsiteRedirectLocation.

Restrictions:

  • The value must start with a slash (/), http://, or https:// and cannot exceed 2 KB.
  • OBS only supports redirection of objects that are in the root directory.

Value range:

None

Default value:

None

version_id

const char *

No

Explanation:

Object version ID. If the object has no version ID, the value is NULL.

Restrictions:

None

Value range:

The value must contain 32 characters.

Default value:

None

meta_data_count

int

No

Explanation:

Number of elements in the meta_data array.

Restrictions:

None

Value range:

None

Default value:

None

meta_data

const obs_name_value *

No

Explanation:

Custom metadata of the object. You can add custom metadata headers that start with x-obs-meta- for easy object management. When you retrieve or query the metadata of the object, the added custom metadata headers will be returned in the response.

Restrictions:

None

use_server_side_encryption

char

No

Explanation:

If server-side encryption is enabled, this parameter is set to '\1'.

Restrictions:

None

Value range:

None

Default value:

None

allow_origin

const char *

No

Explanation:

Returned if the request origin meets the CORS configured on the server.

Restrictions:

None

Value range:

The value that complies with the CORS

Default value:

None

allow_headers

const char *

No

Explanation:

Returned if the request headers meet the CORS configured on the server.

Restrictions:

At most one asterisk (*) is allowed. Spaces, ampersands (&), colons (:), less-than signs (<), and full-width characters are not allowed.

Value range:

The value that complies with the CORS

Default value:

None

max_age

const char *

No

Explanation:

MaxAgeSeconds in the CORS rules of the bucket. It specifies the time your client can cache the response for a cross-origin request.

Restrictions:

Each CORS rule can contain at most one MaxAgeSeconds.

Value range:

An integer greater than or equal to 0, in seconds.

Default value:

3000

allow_methods

const char *

No

Explanation:

Indicates that methods in the rule are included in the response if Access-Control-Request-Method in the request meets the CORS configuration requirements when CORS is configured for buckets.

Restrictions:

None

Value range:

  • GET
  • PUT
  • HEAD
  • POST
  • DELETE

Value range:

None

expose_headers

const char *

No

Explanation:

ExposeHeader in the CORS rules of the bucket. It specifies additional headers allowed in the response by a CORS rule. These headers provide extra information to clients. By default, a browser can access only headers Content-Length and Content-Type. If the browser needs to access other headers, you need to configure them as additional headers.

Restrictions:

Spaces, asterisks (*), ampersands (&), colons (:), less-than signs (<), and full-width characters are not allowed.

Value range:

None

Default value:

None

storage_class

const char *

No

Explanation:

Object storage class.

Restrictions:

This header is returned only when the storage class of an object is not Standard.

Value range:

  • WARM (Infrequent Access storage class)
  • COLD (Archive storage class)

Default value:

None

server_side_encryption

const char *

No

Explanation:

The encryption method used by the server.

Example: x-obs-server-side-encryption:kms

Restrictions:

This header is included in a response if SSE-KMS is used.

Value range:

  • kms (SSE-KMS encryption)
  • obs (SSE-OBS encryption)

Default value:

None

kms_key_id

const char *

No

Explanation:

Key ID. If the SSE-KMS encryption is used with a specified key, the key ID is required.

Restrictions:

This header can only be used when you specify kms for the server_side_encryption header.

Value range:

None

Default value:

If you specify kms for encryption but do not specify a key ID, the default master key will be used. If there is not a default master key, OBS will create one and use it.

customer_algorithm

const char *

No

Explanation:

Indicates a decryption algorithm. This header is included in a response if SSE-C is used.

Restrictions:

None

Value range:

AES256 (AES256 decryption algorithm)

Default value:

None

customer_key_md5

const char *

No

Explanation:

Indicates the MD5 value of a key used to decrypt objects. This header is included in a response if SSE-C is used.

Restrictions:

Base64-encoded MD5 value of the key, for example, 4XvB3tbNTN+tIEVa0/fGaQ==

Value range:

Base64-encoded MD5 value of the key ID.

Default value:

None

bucket_location

const char *

No

Explanation:

Indicates the region where the bucket resides.

Restrictions:

None

Value range:

None

Default value:

None

obs_version

const char *

No

Explanation:

OBS version of the bucket.

Restrictions:

None

Value range:

  • 3.0: bucket of the latest version
  • --: bucket of an earlier version

Default value:

None

restore

const char *

No

Explanation:

Restoration status of an object.

Examples: ongoing-request="true" (the object is being restored); ongoing-request="false", expiry-date="Wed, 7 Nov 2012 00:00:00 GMT" (the object has been restored) expiry-date indicates when the restored object will expire.

Restrictions:

For an Archive object that is being restored or has been restored, this header is returned.

Value range:

None

Default value:

None

obs_object_type

const char *

No

Explanation:

Type of the object.

Restrictions:

This header is returned only when the object is not a Normal object.

Value range:

Appendable

Default value:

None

obs_next_append_position

const char *

No

Explanation:

Indicates the position to be provided for the next request.

Restrictions:

This header is returned only when the object is an Appendable object.

Value range:

None

Default value:

None

obs_head_epid

const char *

No

Explanation:

Enterprise project ID for the current bucket. Users who have enabled the enterprise project function can obtain the ID from the enterprise project service.

Restrictions:

The value is a UUID. This parameter is not required if you have not enabled an enterprise project.

Value range:

None

Default value:

None

reserved_indicator

const char *

No

Explanation:

A special symbol that helps troubleshoot.

Restrictions:

None

Value range:

None

Default value:

None

Table 25 obs_error_details

Parameter

Type

Description

message

const char*

Explanation:

Error details in the XML error response body.

Restrictions:

None

Value range:

See Error Codes.

Default value:

None

resource

const char*

Explanation:

Bucket or object related to the error.

Restrictions:

None

Value range:

None

Default value:

None

further_details

const char*

Explanation:

The value of the FurtherDetails element in the XML error response body.

Restrictions:

None

Value range:

None

Default value:

None

extra_details_count

int

Explanation:

The number of other elements in the XML error response body.

Restrictions:

None

Value range:

None

Default value:

None

extra_details

obs_name_value*

Explanation:

Values of other elements in the XML error response body.

Restrictions:

None

error_headers_count

int

Explanation:

Number of headers in error_headers.

Restrictions:

None

Value range:

None

Default value:

None

error_headers

char**

Explanation:

All response headers that contain the error.

Restrictions:

None

Value range:

None

Default value:

None

Table 26 obs_name_value

Parameter

Type

Mandatory (Yes/No)

Description

name

char *

No

Explanation:

Key of a property.

Restrictions:

None

Value range:

None

Default value:

None

value

char *

No

Explanation:

Property value.

Restrictions:

None

Value range:

None

Default value:

None

Table 27 obs_status

Value

Description

OBS_STATUS_OK

The request is successful.

OBS_STATUS_InitCurlFailed

Failed to initialize curl.

OBS_STATUS_InternalError

Internal error.

OBS_STATUS_OutOfMemory

The local memory is insufficient.

OBS_STATUS_FailedToIInitializeRequest

Failed to initialize the request.

OBS_STATUS_ConnectionFailed

Network connection failed.

OBS_STATUS_XmlParseFailure

Failed to parse the XML file.

OBS_STATUS_NameLookupError

Domain name resolution failed.

OBS_STATUS_FailedToConnect

Failed to connect to the server.

OBS_STATUS_PartialFile

Network transmission.

OBS_STATUS_InvalidParameter

Invalid parameter.

OBS_STATUS_NoToken

The current number of concurrent tasks exceeds the maximum number (1000 by default). Use the set_online_request_max_count function to adjust the maximum number of concurrent tasks.

OBS_STATUS_OpenFileFailed

Failed to open the file.

OBS_STATUS_AccessDenied

The request is rejected.

OBS_STATUS_MalformedPolicy

The format of the request policy is incorrect.

OBS_STATUS_MalformedXML

The XML request format is incorrect.

OBS_STATUS_MethodNotAllowed

The request method is not allowed.

OBS_STATUS_SignatureDoesNotMatch

The signatures do not match. Check whether the AK, SK, and token are correct.

OBS_STATUS_ServiceUnavailable

Server exception.

OBS_STATUS_SlowDown

The request frequency is too high.

Code Examples: Setting the MIME Type for an Object

This example sets the MIME type when uploading a file. If the MIME type is not set, the C SDK will automatically identify the MIME type based on the extension of the file. For example, the MIME type of .xml files is application/xml and that of .html files is text/html.
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
#include "eSDKOBS.h"
#include <stdio.h>
#include <sys/stat.h>
// The response callback function. The content of properties in the callback can be recorded in callback_data (custom callback data).
obs_status response_properties_callback(const obs_response_properties *properties, void *callback_data);
int put_file_data_callback(int buffer_size, char *buffer,
    void *callback_data);
void put_file_complete_callback(obs_status status,
    const obs_error_details *error,
    void *callback_data);
typedef struct put_file_object_callback_data
{
    FILE *infile;
    uint64_t content_length;
    obs_status ret_status;
} put_file_object_callback_data;
uint64_t open_file_and_get_length(char *localfile, put_file_object_callback_data *data);
int main()
{
    // The following code uses file upload as an example to describe how to set the MIME type for an object:
    // Call the obs_initialize method at the program entry to initialize global resources such as the network and memory.
    obs_initialize(OBS_INIT_ALL); 
    obs_options options;
    // Create and initialize options, including the access domain name (host_name), access keys (access_key_id and access_key_secret), bucket name (bucket_name), and bucket storage class (storage_class).
    init_obs_options(&options);
    // Enter the endpoint corresponding to the bucket for host_name. CN-Hong Kong is used here as an example. Replace it with the one in your actual situation.
    options.bucket_options.host_name = "obs.ap-southeast-1.myhuaweicloud.com";
    // Hard-coded or plaintext AK and SK are risky. For security purposes, encrypt your AK and SK and store them in the configuration file or environment variables.
    // In this example, the AK and SK are stored in environment variables for identity authentication. Before running the code in this example, configure local environment variables ACCESS_KEY_ID and SECRET_ACCESS_KEY.
    options.bucket_options.access_key = getenv("ACCESS_KEY_ID");
    options.bucket_options.secret_access_key = getenv("SECRET_ACCESS_KEY");
    // Specify the bucket name, for example, example-bucket-name.
    char * bucketName = "example-bucket-name";
    options.bucket_options.bucket_name = bucketName;
    // Initialize the properties of the object to be uploaded.
    obs_put_properties put_properties;
    init_put_properties(&put_properties);
    // Name of the object to be uploaded
    char *key = "example_put_file_test";
    // Uploaded file
    char file_name[256] = "./example_local_file_test.txt";
    uint64_t content_length = 0;
    // Initialize the structure for storing the uploaded data.
    put_file_object_callback_data data;
    memset(&data, 0, sizeof(put_file_object_callback_data));
    // Open the file and obtain the file length.
    content_length = open_file_and_get_length(file_name, &data);
    // Set the callback function.
    obs_put_object_handler putobjectHandler =
    {
        { &response_properties_callback, &put_file_complete_callback },
        &put_file_data_callback
    };
    // Set the MIME type.
    put_properties.content_type = "text/plain";
    put_object(&options, key, content_length, &put_properties, 0, &putobjectHandler, &data);
    if (OBS_STATUS_OK == data.ret_status) {
        printf("put object from file successfully. \n");
    }
    else
    {
        printf("put object failed(%s).\n",
            obs_get_status_name(data.ret_status));
    }
    if (data.infile != NULL) {
        fclose(data.infile);
    }
    // Release the allocated global resources.
    obs_deinitialize();
}
// The response callback function. The content of properties in the callback can be recorded in callback_data (custom callback data).
obs_status response_properties_callback(const obs_response_properties *properties, void *callback_data)
{
    if (properties == NULL)
    {
        printf("error! obs_response_properties is null!");
        if (callback_data != NULL)
        {
            obs_sever_callback_data *data = (obs_sever_callback_data *)callback_data;
            printf("server_callback buf is %s, len is %llu",
                data->buffer, data->buffer_len);
            return OBS_STATUS_OK;
        }
        else {
            printf("error! obs_sever_callback_data is null!");
            return OBS_STATUS_OK;
        }
    }
    // Print the response.
#define print_nonnull(name, field)                                 \
    do {                                                           \
        if (properties-> field) {                                  \
            printf("%s: %s\n", name, properties->field);          \
        }                                                          \
    } while (0)
    print_nonnull("request_id", request_id);
    print_nonnull("request_id2", request_id2);
    print_nonnull("content_type", content_type);
    if (properties->content_length) {
        printf("content_length: %llu\n", properties->content_length);
    }
    print_nonnull("server", server);
    print_nonnull("ETag", etag);
    print_nonnull("expiration", expiration);
    print_nonnull("website_redirect_location", website_redirect_location);
    print_nonnull("version_id", version_id);
    print_nonnull("allow_origin", allow_origin);
    print_nonnull("allow_headers", allow_headers);
    print_nonnull("max_age", max_age);
    print_nonnull("allow_methods", allow_methods);
    print_nonnull("expose_headers", expose_headers);
    print_nonnull("storage_class", storage_class);
    print_nonnull("server_side_encryption", server_side_encryption);
    print_nonnull("kms_key_id", kms_key_id);
    print_nonnull("customer_algorithm", customer_algorithm);
    print_nonnull("customer_key_md5", customer_key_md5);
    print_nonnull("bucket_location", bucket_location);
    print_nonnull("obs_version", obs_version);
    print_nonnull("restore", restore);
    print_nonnull("obs_object_type", obs_object_type);
    print_nonnull("obs_next_append_position", obs_next_append_position);
    print_nonnull("obs_head_epid", obs_head_epid);
    print_nonnull("reserved_indicator", reserved_indicator);
    int i;
    for (i = 0; i < properties->meta_data_count; i++) {
        printf("x-obs-meta-%s: %s\n", properties->meta_data[i].name,
            properties->meta_data[i].value);
    }
    return OBS_STATUS_OK;
}
int put_file_data_callback(int buffer_size, char *buffer,
    void *callback_data)
{
    put_file_object_callback_data *data =
        (put_file_object_callback_data *)callback_data;
    int ret = 0;
    if (data->content_length) {
        int toRead = ((data->content_length > (unsigned)buffer_size) ?
            (unsigned)buffer_size : data->content_length);
        ret = fread(buffer, 1, toRead, data->infile);
    }
    uint64_t originalContentLength = data->content_length;
    data->content_length -= ret;
    if (data->content_length) {
        printf("%llu bytes remaining ", (unsigned long long)data->content_length);
        printf("(%d%% complete) ...\n",
            (int)(((originalContentLength - data->content_length) * 100) / originalContentLength));
    }
    return ret;
}
void put_file_complete_callback(obs_status status,
    const obs_error_details *error,
    void *callback_data)
{
    put_file_object_callback_data *data = (put_file_object_callback_data *)callback_data;
    data->ret_status = status;
}
uint64_t open_file_and_get_length(char *localfile, put_file_object_callback_data *data)
{
    uint64_t content_length = 0;
    const char *body = 0;
    if (!content_length)
    {
        struct stat statbuf;
        if (stat(localfile, &statbuf) == -1)
        {
            fprintf(stderr, "\nERROR: Failed to stat file %s: ",
                localfile);
            return 0;
        }
        content_length = statbuf.st_size;
    }
    if (!(data->infile = fopen(localfile, "rb")))
    {
        fprintf(stderr, "\nERROR: Failed to open input file %s: ",
            localfile);
        return 0;
    }
    data->content_length = content_length;
    return content_length;
}

Code Examples: Setting the Storage Class for an Object

This example sets the storage class for an object during upload.
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
#include "eSDKOBS.h"
#include <stdio.h>
#include <sys/stat.h>
// The response callback function. The content of properties in the callback can be recorded in callback_data (custom callback data).
obs_status response_properties_callback(const obs_response_properties *properties, void *callback_data);
int put_file_data_callback(int buffer_size, char *buffer,
    void *callback_data);
void put_file_complete_callback(obs_status status,
    const obs_error_details *error,
    void *callback_data);
typedef struct put_file_object_callback_data
{
    FILE *infile;
    uint64_t content_length;
    obs_status ret_status;
} put_file_object_callback_data;
uint64_t open_file_and_get_length(char *localfile, put_file_object_callback_data *data);
int main()
{
    // The following example shows how to set the storage class for an object during upload:
    // Call the obs_initialize method at the program entry to initialize global resources such as the network and memory.
    obs_initialize(OBS_INIT_ALL); 
    obs_options options;
    // Create and initialize options, including the access domain name (host_name), access keys (access_key_id and access_key_secret), bucket name (bucket_name), and bucket storage class (storage_class).
    init_obs_options(&options);
    // Enter the endpoint corresponding to the bucket for host_name. CN-Hong Kong is used here as an example. Replace it with the one in your actual situation.
    options.bucket_options.host_name = "obs.ap-southeast-1.myhuaweicloud.com";
    // Hard-coded or plaintext AK and SK are risky. For security purposes, encrypt your AK and SK and store them in the configuration file or environment variables.
    // In this example, the AK and SK are stored in environment variables for identity authentication. Before running the code in this example, configure local environment variables ACCESS_KEY_ID and SECRET_ACCESS_KEY.
    options.bucket_options.access_key = getenv("ACCESS_KEY_ID");
    options.bucket_options.secret_access_key = getenv("SECRET_ACCESS_KEY");
    // Specify the bucket name, for example, example-bucket-name.
    char * bucketName = "example-bucket-name";
    options.bucket_options.bucket_name = bucketName;
    //Set the storage class to Archive.
    options.bucket_options.storage_class = OBS_STORAGE_CLASS_GLACIER;
    // Initialize the properties of the object to be uploaded.
    obs_put_properties put_properties;
    init_put_properties(&put_properties);
    // Name of the object to be uploaded
    char *key = "example_put_file_test_cold";
    // Uploaded file
    char file_name[256] = "./example_local_file_test.txt";
    uint64_t content_length = 0;
    // Initialize the structure for storing the uploaded data.
    put_file_object_callback_data data;
    memset(&data, 0, sizeof(put_file_object_callback_data));
    // Open the file and obtain the file length.
    content_length = open_file_and_get_length(file_name, &data);
    // Set the callback function.
    obs_put_object_handler putobjectHandler =
    {
        { &response_properties_callback, &put_file_complete_callback },
        &put_file_data_callback
    };
    put_object(&options, key, content_length, &put_properties, 0, &putobjectHandler, &data);
    if (OBS_STATUS_OK == data.ret_status) {
        printf("put object from file successfully. \n");
    }
    else
    {
        printf("put object failed(%s).\n",
            obs_get_status_name(data.ret_status));
    }
    if (data.infile != NULL) {
        fclose(data.infile);
    }
    // Release the allocated global resources.
    obs_deinitialize();
}
// The response callback function. The content of properties in the callback can be recorded in callback_data (custom callback data).
obs_status response_properties_callback(const obs_response_properties *properties, void *callback_data)
{
    if (properties == NULL)
    {
        printf("error! obs_response_properties is null!");
        if (callback_data != NULL)
        {
            obs_sever_callback_data *data = (obs_sever_callback_data *)callback_data;
            printf("server_callback buf is %s, len is %llu",
                data->buffer, data->buffer_len);
            return OBS_STATUS_OK;
        }
        else {
            printf("error! obs_sever_callback_data is null!");
            return OBS_STATUS_OK;
        }
    }
    // Print the response.
#define print_nonnull(name, field)                                 \
    do {                                                           \
        if (properties-> field) {                                  \
            printf("%s: %s\n", name, properties->field);          \
        }                                                          \
    } while (0)
    print_nonnull("request_id", request_id);
    print_nonnull("request_id2", request_id2);
    print_nonnull("content_type", content_type);
    if (properties->content_length) {
        printf("content_length: %llu\n", properties->content_length);
    }
    print_nonnull("server", server);
    print_nonnull("ETag", etag);
    print_nonnull("expiration", expiration);
    print_nonnull("website_redirect_location", website_redirect_location);
    print_nonnull("version_id", version_id);
    print_nonnull("allow_origin", allow_origin);
    print_nonnull("allow_headers", allow_headers);
    print_nonnull("max_age", max_age);
    print_nonnull("allow_methods", allow_methods);
    print_nonnull("expose_headers", expose_headers);
    print_nonnull("storage_class", storage_class);
    print_nonnull("server_side_encryption", server_side_encryption);
    print_nonnull("kms_key_id", kms_key_id);
    print_nonnull("customer_algorithm", customer_algorithm);
    print_nonnull("customer_key_md5", customer_key_md5);
    print_nonnull("bucket_location", bucket_location);
    print_nonnull("obs_version", obs_version);
    print_nonnull("restore", restore);
    print_nonnull("obs_object_type", obs_object_type);
    print_nonnull("obs_next_append_position", obs_next_append_position);
    print_nonnull("obs_head_epid", obs_head_epid);
    print_nonnull("reserved_indicator", reserved_indicator);
    int i;
    for (i = 0; i < properties->meta_data_count; i++) {
        printf("x-obs-meta-%s: %s\n", properties->meta_data[i].name,
            properties->meta_data[i].value);
    }
    return OBS_STATUS_OK;
}
int put_file_data_callback(int buffer_size, char *buffer,
    void *callback_data)
{
    put_file_object_callback_data *data =
        (put_file_object_callback_data *)callback_data;
    int ret = 0;
    if (data->content_length) {
        int toRead = ((data->content_length > (unsigned)buffer_size) ?
            (unsigned)buffer_size : data->content_length);
        ret = fread(buffer, 1, toRead, data->infile);
    }
    uint64_t originalContentLength = data->content_length;
    data->content_length -= ret;
    if (data->content_length) {
        printf("%llu bytes remaining ", (unsigned long long)data->content_length);
        printf("(%d%% complete) ...\n",
            (int)(((originalContentLength - data->content_length) * 100) / originalContentLength));
    }
    return ret;
}
void put_file_complete_callback(obs_status status,
    const obs_error_details *error,
    void *callback_data)
{
    put_file_object_callback_data *data = (put_file_object_callback_data *)callback_data;
    data->ret_status = status;
}
uint64_t open_file_and_get_length(char *localfile, put_file_object_callback_data *data)
{
    uint64_t content_length = 0;
    const char *body = 0;
    if (!content_length)
    {
        struct stat statbuf;
        if (stat(localfile, &statbuf) == -1)
        {
            fprintf(stderr, "\nERROR: Failed to stat file %s: ",
                localfile);
            return 0;
        }
        content_length = statbuf.st_size;
    }
    if (!(data->infile = fopen(localfile, "rb")))
    {
        fprintf(stderr, "\nERROR: Failed to open input file %s: ",
            localfile);
        return 0;
    }
    data->content_length = content_length;
    return content_length;
}

Code Examples: Customizing Metadata for an Object

This example customizes metadata for an object during upload.
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
#include "eSDKOBS.h"
#include <stdio.h>
#include <sys/stat.h>
// The response callback function. The content of properties in the callback can be recorded in callback_data (custom callback data).
obs_status response_properties_callback(const obs_response_properties *properties, void *callback_data);
int put_file_data_callback(int buffer_size, char *buffer,
    void *callback_data);
void put_file_complete_callback(obs_status status,
    const obs_error_details *error,
    void *callback_data);
typedef struct put_file_object_callback_data
{
    FILE *infile;
    uint64_t content_length;
    obs_status ret_status;
} put_file_object_callback_data;
uint64_t open_file_and_get_length(char *localfile, put_file_object_callback_data *data);
int main()
{
    // The following example shows how to customize metadata for an object during upload:
    // Call the obs_initialize method at the program entry to initialize global resources such as the network and memory.
    obs_initialize(OBS_INIT_ALL); 
    obs_options options;
    // Create and initialize options, including the access domain name (host_name), access keys (access_key_id and access_key_secret), bucket name (bucket_name), and bucket storage class (storage_class).
    init_obs_options(&options);
    // Enter the endpoint corresponding to the bucket for host_name. CN-Hong Kong is used here as an example. Replace it with the one in your actual situation.
    options.bucket_options.host_name = "obs.ap-southeast-1.myhuaweicloud.com";
    // Hard-coded or plaintext AK and SK are risky. For security purposes, encrypt your AK and SK and store them in the configuration file or environment variables.
    // In this example, the AK and SK are stored in environment variables for identity authentication. Before running the code in this example, configure local environment variables ACCESS_KEY_ID and SECRET_ACCESS_KEY.
    options.bucket_options.access_key = getenv("ACCESS_KEY_ID");
    options.bucket_options.secret_access_key = getenv("SECRET_ACCESS_KEY");
    // Specify the bucket name, for example, example-bucket-name.
    char * bucketName = "example-bucket-name";
    options.bucket_options.bucket_name = bucketName;
    // Initialize the properties of the object to be uploaded.
    obs_put_properties put_properties;
    init_put_properties(&put_properties);
    // Name of the object to be uploaded
    char *key = "example_put_file_test_with_matadatas";
    // Uploaded file
    char file_name[256] = "./example_local_file_test.txt";
    uint64_t content_length = 0;
    // Initialize the structure for storing the uploaded data.
    put_file_object_callback_data data;
    memset(&data, 0, sizeof(put_file_object_callback_data));
    // Open the file and obtain the file length.
    content_length = open_file_and_get_length(file_name, &data);
    // Set the callback function.
    obs_put_object_handler putobjectHandler =
    {
        { &response_properties_callback, &put_file_complete_callback },
        &put_file_data_callback
    };
    //Set the custom metadata.
    obs_name_value example_matadatas[2] = {0};
    example_matadatas[0].name = "example-property1";
    example_matadatas[0].value = "example-property-value1";
    example_matadatas[1].name = "example-property2";
    example_matadatas[1].value = "example-property-value2";
    put_properties.meta_data = &example_matadatas;
    //Set the custom metadata count.
    put_properties.meta_data_count = 2;
    put_object(&options, key, content_length, &put_properties, 0, &putobjectHandler, &data);
    if (OBS_STATUS_OK == data.ret_status) {
        printf("put object from file successfully. \n");
    }
    else
    {
        printf("put object failed(%s).\n",
            obs_get_status_name(data.ret_status));
    }
    if (data.infile != NULL) {
        fclose(data.infile);
    }
    // Release the allocated global resources.
    obs_deinitialize();
}
// The response callback function. The content of properties in the callback can be recorded in callback_data (custom callback data).
obs_status response_properties_callback(const obs_response_properties *properties, void *callback_data)
{
    if (properties == NULL)
    {
        printf("error! obs_response_properties is null!");
        if (callback_data != NULL)
        {
            obs_sever_callback_data *data = (obs_sever_callback_data *)callback_data;
            printf("server_callback buf is %s, len is %llu",
                data->buffer, data->buffer_len);
            return OBS_STATUS_OK;
        }
        else {
            printf("error! obs_sever_callback_data is null!");
            return OBS_STATUS_OK;
        }
    }
    // Print the response.
#define print_nonnull(name, field)                                 \
    do {                                                           \
        if (properties-> field) {                                  \
            printf("%s: %s\n", name, properties->field);          \
        }                                                          \
    } while (0)
    print_nonnull("request_id", request_id);
    print_nonnull("request_id2", request_id2);
    print_nonnull("content_type", content_type);
    if (properties->content_length) {
        printf("content_length: %llu\n", properties->content_length);
    }
    print_nonnull("server", server);
    print_nonnull("ETag", etag);
    print_nonnull("expiration", expiration);
    print_nonnull("website_redirect_location", website_redirect_location);
    print_nonnull("version_id", version_id);
    print_nonnull("allow_origin", allow_origin);
    print_nonnull("allow_headers", allow_headers);
    print_nonnull("max_age", max_age);
    print_nonnull("allow_methods", allow_methods);
    print_nonnull("expose_headers", expose_headers);
    print_nonnull("storage_class", storage_class);
    print_nonnull("server_side_encryption", server_side_encryption);
    print_nonnull("kms_key_id", kms_key_id);
    print_nonnull("customer_algorithm", customer_algorithm);
    print_nonnull("customer_key_md5", customer_key_md5);
    print_nonnull("bucket_location", bucket_location);
    print_nonnull("obs_version", obs_version);
    print_nonnull("restore", restore);
    print_nonnull("obs_object_type", obs_object_type);
    print_nonnull("obs_next_append_position", obs_next_append_position);
    print_nonnull("obs_head_epid", obs_head_epid);
    print_nonnull("reserved_indicator", reserved_indicator);
    int i;
    for (i = 0; i < properties->meta_data_count; i++) {
        printf("x-obs-meta-%s: %s\n", properties->meta_data[i].name,
            properties->meta_data[i].value);
    }
    return OBS_STATUS_OK;
}
int put_file_data_callback(int buffer_size, char *buffer,
    void *callback_data)
{
    put_file_object_callback_data *data =
        (put_file_object_callback_data *)callback_data;
    int ret = 0;
    if (data->content_length) {
        int toRead = ((data->content_length > (unsigned)buffer_size) ?
            (unsigned)buffer_size : data->content_length);
        ret = fread(buffer, 1, toRead, data->infile);
    }
    uint64_t originalContentLength = data->content_length;
    data->content_length -= ret;
    if (data->content_length) {
        printf("%llu bytes remaining ", (unsigned long long)data->content_length);
        printf("(%d%% complete) ...\n",
            (int)(((originalContentLength - data->content_length) * 100) / originalContentLength));
    }
    return ret;
}
void put_file_complete_callback(obs_status status,
    const obs_error_details *error,
    void *callback_data)
{
    put_file_object_callback_data *data = (put_file_object_callback_data *)callback_data;
    data->ret_status = status;
}
uint64_t open_file_and_get_length(char *localfile, put_file_object_callback_data *data)
{
    uint64_t content_length = 0;
    const char *body = 0;
    if (!content_length)
    {
        struct stat statbuf;
        if (stat(localfile, &statbuf) == -1)
        {
            fprintf(stderr, "\nERROR: Failed to stat file %s: ",
                localfile);
            return 0;
        }
        content_length = statbuf.st_size;
    }
    if (!(data->infile = fopen(localfile, "rb")))
    {
        fprintf(stderr, "\nERROR: Failed to open input file %s: ",
            localfile);
        return 0;
    }
    data->content_length = content_length;
    return content_length;
}

Usamos cookies para aprimorar nosso site e sua experiência. Ao continuar a navegar em nosso site, você aceita nossa política de cookies. Saiba mais

Feedback

Feedback

Feedback

0/500

Selected Content

Submit selected content with the feedback