本文介绍如何使用上传回调。
上传回调的完整代码请参见GitHub。
以下代码用于上传回调(callback)。
#include "oss_api.h" #include "aos_http_io.h" const char *endpoint = "<yourEndpoint>"; const char *access_key_id = "<yourAccessKeyId>"; const char *access_key_secret = "<yourAccessKeySecret>"; const char *bucket_name = "<yourBucketName>"; const char *object_name = "<yourObjectName>"; const char *object_content = "More than just cloud."; void init_options(oss_request_options_t *options) { options->config = oss_config_create(options->pool); /* 用char*类型的字符串初始化aos_string_t类型。*/ aos_str_set(&options->config->endpoint, endpoint); aos_str_set(&options->config->access_key_id, access_key_id); aos_str_set(&options->config->access_key_secret, access_key_secret); /* 是否使用了CNAME。0表示不使用。*/ options->config->is_cname = 0; /* 设置网络相关参数,比如超时时间等。*/ options->ctl = aos_http_controller_create(options->pool, 0); } int main(int argc, char *argv[]) { aos_pool_t *p = NULL; aos_status_t *s = NULL; aos_string_t bucket; aos_string_t object; aos_table_t *headers = NULL; oss_request_options_t *options = NULL; aos_table_t *resp_headers = NULL; aos_list_t resp_body; aos_list_t buffer; aos_buf_t *content; char *buf = NULL; int64_t len = 0; int64_t size = 0; int64_t pos = 0; char b64_buf[1024]; int b64_len; /* 采用JSON格式。*/ /*(可选)设置回调请求消息头中Host的值,如您的服务器配置Host的值。*/ char *callback = "{" "\"callbackUrl\":\"http://oss-demo.aliyuncs.com:23450\"," "\"callbackHost\":\"yourCallbackHost\"," "\"callbackBody\":\"bucket=${bucket}&object=${object}&size=${size}&mimeType=${mimeType}\"," "\"callbackBodyType\":\"application/x-www-form-urlencoded\"" "}"; /* 在程序入口调用aos_http_io_initialize方法来初始化网络、内存等全局资源。*/ if (aos_http_io_initialize(NULL, 0) != AOSE_OK) { exit(1); } /* 初始化参数。*/ aos_pool_create(&p, NULL); options = oss_request_options_create(p); init_options(options); aos_str_set(&bucket, bucket_name); aos_str_set(&object, object_name); aos_list_init(&resp_body); aos_list_init(&buffer); content = aos_buf_pack(options->pool, object_content, strlen(object_content)); aos_list_add_tail(&content->node, &buffer); /* 将callback放入header。*/ b64_len = aos_base64_encode((unsigned char*)callback, strlen(callback), b64_buf); b64_buf[b64_len] = '\0'; headers = aos_table_make(p, 1); apr_table_set(headers, OSS_CALLBACK, b64_buf); /* 上传回调。*/ s = oss_do_put_object_from_buffer(options, &bucket, &object, &buffer, headers, NULL, NULL, &resp_headers, &resp_body); if (aos_status_is_ok(s)) { printf("put object from buffer succeeded\n"); } else { printf("put object from buffer failed\n"); } /* 获取buffer长度。*/ len = aos_buf_list_len(&resp_body); buf = (char *)aos_pcalloc(p, (apr_size_t)(len + 1)); buf[len] = '\0'; /* 拷贝buffer内容到内存。*/ aos_list_for_each_entry(aos_buf_t, content, &resp_body, node) { size = aos_buf_size(content); memcpy(buf + pos, content->pos, (size_t)size); pos += size; } /* 释放内存池,相当于释放了请求过程中各资源分配的内存。*/ aos_pool_destroy(p); /* 释放之前分配的全局资源。*/ aos_http_io_deinitialize(); return 0; }