Upload callbacks let your application server react immediately after an object lands in OSS — no polling required. Include callback parameters in the upload request, and OSS automatically sends an HTTP POST request to your server once the upload completes.
Common use cases include:
Database updates: Record the uploaded object's metadata (bucket name, object key, size, MIME type) in your database.
Media processing: Trigger transcoding or thumbnail generation as soon as a video or image is uploaded.
Third-party direct uploads: Let clients upload directly to OSS while your server is notified of each completed upload, without handling the file transfer itself.
How it works
The client includes callback parameters in the upload request sent to OSS.
After the upload completes, OSS sends an HTTP POST request to the
callbackUrl— the public URL of your application server.Your application server receives the POST request, performs follow-up operations (such as updating a database), and returns a response to OSS.
After OSS receives the response, OSS returns the upload result to the client.
The POST request body contains two categories of parameters:
System-defined parameters: Standard upload metadata such as bucket name, object key, object size, and MIME type. See System-defined callback variables.
Custom parameters: Application-specific values you define (for example, a user ID or session token). Custom parameter keys must start with
x:.
Supported upload methods
Only the following upload operations support callbacks:
| Upload method | API operation |
|---|---|
| Simple upload | PutObject |
| Form upload | PostObject |
| Multipart upload | CompleteMultipartUpload |
System-defined callback variables
Use these variables in your callbackBody template to include upload metadata in the callback request body:
| Variable | Description | Example value |
|---|---|---|
${bucket} | Name of the bucket | examplebucket |
${object} | Full path of the uploaded object | exampledir/exampleobject.txt |
${etag} | ETag of the object | 5B3C1A2E053D763E1B002CC607C5A0FE |
${size} | Object size in bytes | 1024 |
${mimeType} | MIME type of the object | image/jpeg |
${imageInfo.height} | Image height in pixels (images only) | 600 |
${imageInfo.width} | Image width in pixels (images only) | 800 |
${imageInfo.format} | Image format (images only) | jpeg |
${x:<key>} | Custom variable (replace <key> with your variable name) | ${x:user_id} |
Example: A callbackBody of bucket=${bucket}&object=${object}&size=${size} causes OSS to send a POST body like:
bucket=examplebucket&object=exampledir/exampleobject.txt&size=1024Usage notes
Object storage is not affected by callback failures
The uploaded object is stored in OSS regardless of whether the callback succeeds or fails. If your callback server is unreachable or returns an error, the object remains in OSS and the upload result returned to the client reflects the callback failure.
Configure upload callbacks using OSS SDKs
The following examples show how to configure upload callbacks using OSS SDKs. For other languages, see Overview.
All examples use callbackUrl and callbackBody to define where OSS sends the callback and what information the request body contains. Custom variables (prefixed with x:) are passed alongside the callback parameters.
Prerequisites
Before you begin, make sure that:
The
OSS_ACCESS_KEY_IDandOSS_ACCESS_KEY_SECRETenvironment variables are set with valid credentials.Your callback server is publicly accessible and can receive HTTP POST requests from OSS.
<details> <summary>Python</summary>
import base64
import argparse
import alibabacloud_oss_v2 as oss
parser = argparse.ArgumentParser(description="put object sample")
# Add required parameters
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
parser.add_argument('--key', help='The name of the object.', required=True)
parser.add_argument('--call_back_url', help='Callback server address.', required=True)
def main():
args = parser.parse_args()
# Obtain access credentials from environment variables
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
# Configure the SDK client
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
cfg.region = args.region
if args.endpoint is not None:
cfg.endpoint = args.endpoint
# Create an OSS client
client = oss.Client(cfg)
# Content to upload (string)
data = 'hello world'
# Construct callback parameters: specify the callback address and callback request body, using Base64 encoding
callback=base64.b64encode(str('{\"callbackUrl\":\"' + args.call_back_url + '\",\"callbackBody\":\"bucket=${bucket}&object=${object}&my_var_1=${x:var1}&my_var_2=${x:var2}\"}').encode()).decode(),
# Construct custom variables (callback-var), using Base64 encoding
callback_var=base64.b64encode('{\"x:var1\":\"value1\",\"x:var2\":\"value2\"}'.encode()).decode(),
# Initiate the upload request with callback parameters
result = client.put_object(oss.PutObjectRequest(
bucket=args.bucket,
key=args.key,
body=data,
callback=callback,
callback_var=callback_var,
))
# Print the return result (including status code, request ID, etc.)
print(vars(result))
if __name__ == "__main__":
main()</details>
<details> <summary>Java</summary>
import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.Callback;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import java.io.ByteArrayInputStream;
public class Demo {
public static void main(String[] args) throws Exception{
// Specify the endpoint of the region. In this example, the endpoint of the China (Hangzhou) region is used.
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 name of the bucket. Example: examplebucket.
String bucketName = "examplebucket";
// Specify the full path of the object. Example: exampledir/exampleobject.txt. Do not include the bucket name in the full path.
String objectName = "exampledir/exampleobject.txt";
// Specify the address of the server to which the callback request is sent. Example: https://example.com:23450.
String callbackUrl = "<your-callback-server-url>";
// 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 and set the signature version to V4.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
String content = "Hello OSS";
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName,new ByteArrayInputStream(content.getBytes()));
// Configure upload callback parameters.
Callback callback = new Callback();
callback.setCallbackUrl(callbackUrl);
// (Optional) Specify the CallbackHost field in the callback request header.
// callback.setCallbackHost("<your-callback-host>");
// Set the callback request body in JSON format and define placeholder variables within.
callback.setCalbackBodyType(Callback.CalbackBodyType.JSON);
callback.setCallbackBody("{\\\"bucket\\\":${bucket},\\\"object\\\":${object},\\\"mimeType\\\":${mimeType},\\\"size\\\":${size},\\\"my_var1\\\":${x:var1},\\\"my_var2\\\":${x:var2}}");
// Configure custom parameters for the callback request. Each custom parameter consists of a key and a value. The key must start with x:.
callback.addCallbackVar("x:var1", "value1");
callback.addCallbackVar("x:var2", "value2");
putObjectRequest.setCallback(callback);
// Perform the upload operation.
PutObjectResult putObjectResult = ossClient.putObject(putObjectRequest);
// Read the message content returned from the upload callback.
byte[] buffer = new byte[1024];
putObjectResult.getResponse().getContent().read(buffer);
// Close the stream after reading to prevent connection leaks.
putObjectResult.getResponse().getContent().close();
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
} catch (Throwable 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();
}
}
}
}</details>
<details> <summary>Go</summary>
package main
import (
"context"
"encoding/base64"
"encoding/json"
"flag"
"log"
"strings"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)
var (
region string // The region in which the bucket is located.
bucketName string // The name of the bucket.
objectName string // The name of the object.
)
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() {
flag.Parse()
if len(bucketName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, bucket name required")
}
if len(region) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, region required")
}
if len(objectName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, object name required")
}
// Load the default configurations and specify the credential provider and region.
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion(region)
// Create an OSSClient instance.
client := oss.NewClient(cfg)
// Specify the callback parameters.
callbackMap := map[string]string{
"callbackUrl": "http://example.com:23450", // Specify the URL of the callback server.
"callbackBody": "bucket=${bucket}&object=${object}&size=${size}&my_var_1=${x:my_var1}&my_var_2=${x:my_var2}", // Specify the callback request body.
"callbackBodyType": "application/x-www-form-urlencoded", // Specify the type of the callback request body.
}
// Convert the callback parameters to a JSON string and encode in Base64.
callbackStr, err := json.Marshal(callbackMap)
if err != nil {
log.Fatalf("failed to marshal callback map: %v", err)
}
callbackBase64 := base64.StdEncoding.EncodeToString(callbackStr)
callbackVarMap := map[string]string{}
callbackVarMap["x:my_var1"] = "this is var 1"
callbackVarMap["x:my_var2"] = "this is var 2"
callbackVarStr, err := json.Marshal(callbackVarMap)
if err != nil {
log.Fatalf("failed to marshal callback var: %v", err)
}
callbackVarBase64 := base64.StdEncoding.EncodeToString(callbackVarStr)
body := strings.NewReader("Hello, OSS!")
// Create a PutObject request with callback parameters.
request := &oss.PutObjectRequest{
Bucket: oss.Ptr(bucketName),
Key: oss.Ptr(objectName),
Body: body,
Callback: oss.Ptr(callbackBase64),
CallbackVar: oss.Ptr(callbackVarBase64),
}
result, err := client.PutObject(context.TODO(), request)
if err != nil {
log.Fatalf("failed to put object %v", err)
}
log.Printf("put object result:%#v\n", result)
}</details>
<details> <summary>PHP</summary>
<?php
// Introduce autoload files to load dependent libraries.
require_once __DIR__ . '/../vendor/autoload.php';
use AlibabaCloud\Oss\V2 as Oss;
// Specify descriptions for command line parameters.
$optsdesc = [
"region" => ['help' => 'The region in which the bucket is located.', 'required' => True],
"endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False],
"bucket" => ['help' => 'The name of the bucket.', 'required' => True],
"key" => ['help' => 'The name of the object.', 'required' => True],
];
// Convert the parameter descriptions to a long options list required by getopt.
$longopts = \array_map(function ($key) {
return "$key:";
}, array_keys($optsdesc));
// Parse the command line parameters.
$options = getopt("", $longopts);
// Check whether the required parameters are configured.
foreach ($optsdesc as $key => $value) {
if ($value['required'] === True && empty($options[$key])) {
$help = $value['help'];
echo "Error: the following arguments are required: --$key, $help" . PHP_EOL;
exit(1);
}
}
$region = $options["region"];
$bucket = $options["bucket"];
$key = $options["key"];
// Obtain access credentials from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();
// Use the default configurations of the SDK.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider);
$cfg->setRegion($region);
if (isset($options["endpoint"])) {
$cfg->setEndpoint($options["endpoint"]);
}
// Create an OSSClient instance.
$client = new Oss\Client($cfg);
// Specify the callback parameters.
// Replace the placeholder values with your actual callback server URL and hostname.
$callback = base64_encode(json_encode(array(
'callbackUrl' => '<your-callback-server-url>',
'callbackHost' => '<your-callback-host>',
'callbackBody' => 'bucket=${bucket}&object=${object}&etag=${etag}&size=${size}&mimeType=${mimeType}&imageInfo.height=${imageInfo.height}&imageInfo.width=${imageInfo.width}&imageInfo.format=${imageInfo.format}&my_var1=${x:var1}&my_var2=${x:var2}',
'callbackBodyType' => "application/x-www-form-urlencoded",
)));
// Specify custom variables to pass additional information in the callback.
$callbackVar = base64_encode(json_encode(array(
'x:var1' => "value1",
'x:var2' => 'value2',
)));
// Create a PutObjectRequest and attach the callback parameters.
$request = new Oss\Models\PutObjectRequest(bucket: $bucket, key: $key);
$request->callback = $callback;
$request->callbackVar = $callbackVar;
// Execute the upload request.
$result = $client->putObject($request);
// Display the result.
printf(
'status code:' . $result->statusCode . PHP_EOL .
'request id:' . $result->requestId . PHP_EOL .
'callback result:' . var_export($result->callbackResult, true) . PHP_EOL
);</details>
<details> <summary>Node.js</summary>
const OSS = require("ali-oss");
var path = require("path");
const client = new OSS({
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou.
region: "<your-region>",
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
authorizationV4: true,
// Specify the name of the bucket.
bucket: "examplebucket",
});
const options = {
callback: {
// Specify the address of the callback server that receives the callback request. Example: http://oss-demo.aliyuncs.com:23450.
url: "http://oss-demo.aliyuncs.com:23450",
// (Optional) Specify the Host field included in the callback request header.
//host: '<your-callback-host>',
// Specify the body of the callback request.
body: "bucket=${bucket}&object=${object}&var1=${x:var1}&var2=${x:var2}",
// Specify Content-Type in the callback request.
contentType: "application/x-www-form-urlencoded",
// Specifies whether OSS sends Server Name Indication (SNI) to the origin address specified by callbackUrl when a callback request is initiated from the client.
callbackSNI: true,
// Configure custom parameters for the callback request.
customValue: {
var1: "value1",
var2: "value2",
},
},
};
async function put() {
try {
// Specify the full paths of the object and the local file. Do not include the bucket name in the full path of the object.
let result = await client.put(
"exampleobject.txt",
path.normalize("/localpath/examplefile.txt"),
options
);
console.log(result);
} catch (e) {
console.log(e);
}
}
put();</details>
<details> <summary>C#</summary>
using System;
using System.IO;
using System.Text;
using Aliyun.OSS;
using Aliyun.OSS.Common;
using Aliyun.OSS.Util;
namespace Callback
{
class Program
{
static void Main(string[] args)
{
Program.PutObjectCallback();
Console.ReadKey();
}
public static void PutObjectCallback()
{
// 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. Example: examplebucket.
var bucketName = "examplebucket";
// Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt.
var objectName = "exampledir/exampleobject.txt";
// Specify the full path of the local file that you want to upload. Example: D:\\localpath\\examplefile.txt.
var localFilename = "D:\\localpath\\examplefile.txt";
// Specify the URL of the callback server. Example: https://example.com:23450.
const string callbackUrl = "<your-callback-server-url>";
// Specify the callbackBody field included in the callback request.
const string callbackBody = "bucket=${bucket}&object=${object}&etag=${etag}&size=${size}&mimeType=${mimeType}&" +
"my_var1=${x:var1}&my_var2=${x:var2}";
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
const string endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// 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
{
string responseContent = "";
var metadata = BuildCallbackMetadata(callbackUrl, callbackBody);
using (var fs = File.Open(localFilename, FileMode.Open))
{
var putObjectRequest = new PutObjectRequest(bucketName, objectName, fs, metadata);
var result = client.PutObject(putObjectRequest);
responseContent = GetCallbackResponse(result);
}
Console.WriteLine("Put object:{0} succeeded, callback response content:{1}", objectName, responseContent);
}
catch (OssException ex)
{
Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID: {2}\tHostID: {3}",
ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
}
catch (Exception ex)
{
Console.WriteLine("Failed with error info: {0}", ex.Message);
}
}
// Configure an upload callback.
private static ObjectMetadata BuildCallbackMetadata(string callbackUrl, string callbackBody)
{
string callbackHeaderBuilder = new CallbackHeaderBuilder(callbackUrl, callbackBody).Build();
string CallbackVariableHeaderBuilder = new CallbackVariableHeaderBuilder().
AddCallbackVariable("x:var1", "x:value1").AddCallbackVariable("x:var2", "x:value2").Build();
var metadata = new ObjectMetadata();
metadata.AddHeader(HttpHeaders.Callback, callbackHeaderBuilder);
metadata.AddHeader(HttpHeaders.CallbackVar, CallbackVariableHeaderBuilder);
return metadata;
}
// Read the response to the upload callback request.
private static string GetCallbackResponse(PutObjectResult putObjectResult)
{
string callbackResponse = null;
using (var stream = putObjectResult.ResponseStream)
{
var buffer = new byte[4 * 1024];
var bytesRead = stream.Read(buffer, 0, buffer.Length);
callbackResponse = Encoding.Default.GetString(buffer, 0, bytesRead);
}
return callbackResponse;
}
}
}</details>
<details> <summary>Android (Java)</summary>
// Construct an upload request.
// Specify the name of the bucket, the full path of the object, and the full path of the local file. In this example, the name of the bucket is examplebucket, the full path of the object is exampledir/exampleobject.txt, and the full path of the local file is /storage/emulated/0/oss/examplefile.txt.
// Do not include the bucket name in the full path of the object.
PutObjectRequest put = new PutObjectRequest("examplebucket", "exampledir/exampleobject.txt", "/storage/emulated/0/oss/examplefile.txt");
put.setCallbackParam(new HashMap<String, String>() {
{
put("callbackUrl", "http://oss-demo.aliyuncs.com:23450");
put("callbackHost", "<your-callback-host>");
put("callbackBodyType", "application/json");
put("callbackBody", "{\"mimeType\":${mimeType},\"size\":${size}}");
}
});
OSSAsyncTask task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
@Override
public void onSuccess(PutObjectRequest request, PutObjectResult result) {
Log.d("PutObject", "UploadSuccess");
// Obtain the returned callback information. You can obtain the callback information only if you specify servercallback in the request.
String serverCallbackReturnJson = result.getServerCallbackReturnBody();
Log.d("servercallback", serverCallbackReturnJson);
}
@Override
public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
// Handle exceptions.
}
});</details>
<details> <summary>Objective-C</summary>
OSSPutObjectRequest * request = [OSSPutObjectRequest new];
// Specify the name of the bucket. 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";
request.uploadingFileURL = [NSURL fileURLWithPath:@"<filepath>"];
// Configure callback parameters.
request.callbackParam = @{
@"callbackUrl": @"<your-callback-server-url>",
@"callbackBody": @"<your-callback-body>"
};
// Specify custom variables.
request.callbackVar = @{
@"<var1>": @"<value1>",
@"<var2>": @"<value2>"
};
request.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
NSLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);
};
OSSTask * task = [client putObject:request];
[task continueWithBlock:^id(OSSTask *task) {
if (task.error) {
OSSLogError(@"%@", task.error);
} else {
OSSPutObjectResult * result = task.result;
NSLog(@"Result - requestId: %@, headerFields: %@, servercallback: %@",
result.requestId,
result.httpResponseHeaderFields,
result.serverReturnJsonString);
}
return nil;
}];
// Implement synchronous blocking to wait for the task to complete.
// [task waitUntilFinished];</details>
<details> <summary>C++</summary>
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;
int main(void)
{
/* Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
std::string Endpoint = "<your-endpoint>";
/* Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. */
std::string Region = "<your-region>";
/* Specify the name of the bucket. Example: examplebucket. */
std::string BucketName = "examplebucket";
/* Specify the full path of the object. Do not include the bucket name in the full path of the object. Example: exampledir/exampleobject.txt. */
std::string ObjectName = "exampledir/exampleobject.txt";
/* Specify the URL of the callback server. */
std::string ServerName = "https://example.aliyundoc.com:23450";
/* Initialize resources such as network resources. */
InitializeSdk();
ClientConfiguration conf;
conf.signatureVersion = SignatureVersionType::V4;
/* Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. */
auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
OssClient client(Endpoint, credentialsProvider, conf);
client.SetRegion(Region);
std::shared_ptr<std::iostream> content = std::make_shared<std::stringstream>();
*content << "Thank you for using Aliyun Object Storage Service!";
/* Configure the upload callback parameters. */
std::string callbackBody = "bucket=${bucket}&object=${object}&etag=${etag}&size=${size}&mimeType=${mimeType}&my_var1=${x:var1}";
ObjectCallbackBuilder builder(ServerName, callbackBody, "", ObjectCallbackBuilder::Type::URL);
std::string value = builder.build();
ObjectCallbackVariableBuilder varBuilder;
varBuilder.addCallbackVariable("x:var1", "value1");
std::string varValue = varBuilder.build();
PutObjectRequest request(BucketName, ObjectName, content);
request.MetaData().addHeader("x-oss-callback", value);
request.MetaData().addHeader("x-oss-callback-var", varValue);
auto outcome = client.PutObject(request);
/* Release resources such as network resources. */
ShutdownSdk();
return 0;
}</details>
<details> <summary>C</summary>
#include "oss_api.h"
#include "aos_http_io.h"
/* Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
const char *endpoint = "<your-endpoint>";
/* Specify the name of the bucket. Example: examplebucket. */
const char *bucket_name = "examplebucket";
/* Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt. */
const char *object_name = "exampledir/exampleobject.txt";
const char *object_content = "More than just cloud.";
/* Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. */
const char *region = "<your-region>";
void init_options(oss_request_options_t *options)
{
options->config = oss_config_create(options->pool);
/* Use a char* string to initialize data of the aos_string_t type. */
aos_str_set(&options->config->endpoint, endpoint);
/* Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. */
aos_str_set(&options->config->access_key_id, getenv("OSS_ACCESS_KEY_ID"));
aos_str_set(&options->config->access_key_secret, getenv("OSS_ACCESS_KEY_SECRET"));
aos_str_set(&options->config->region, region);
options->config->signature_version = 4;
/* Specify whether to use CNAME. The value 0 indicates that CNAME is not used. */
options->config->is_cname = 0;
/* Configure network parameters, such as the timeout period. */
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;
/* Specify the callback parameters in the JSON format. */
/* (Optional) Specify the Host field included in the callback request header. */
char *callback = "{"
"\"callbackUrl\":\"http://oss-demo.aliyuncs.com:23450\","
"\"callbackHost\":\"<your-callback-host>\","
"\"callbackBody\":\"bucket=${bucket}&object=${object}&size=${size}&mimeType=${mimeType}\","
"\"callbackBodyType\":\"application/x-www-form-urlencoded\""
"}";
/* Call the aos_http_io_initialize method in main() to initialize global resources, such as network resources and memory resources. */
if (aos_http_io_initialize(NULL, 0) != AOSE_OK) {
exit(1);
}
/* Initialize the parameters. */
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);
/* Add the callback to the header using Base64 encoding. */
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);
/* Configure the upload callback. */
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");
}
/* Obtain the buffer length. */
len = aos_buf_list_len(&resp_body);
buf = (char *)aos_pcalloc(p, (apr_size_t)(len + 1));
buf[len] = '\0';
/* Copy the content in the buffer to the memory. */
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;
}
/* Release the memory pool. This operation releases the memory resources allocated for the request. */
aos_pool_destroy(p);
/* Release the allocated global resources. */
aos_http_io_deinitialize();
return 0;
}</details>
<details> <summary>Ruby</summary>
require 'aliyun/oss'
client = Aliyun::OSS::Client.new(
# In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint.
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.
access_key_id: ENV['OSS_ACCESS_KEY_ID'],
access_key_secret: ENV['OSS_ACCESS_KEY_SECRET']
)
# Specify the name of the bucket. Example: examplebucket.
bucket = client.get_bucket('examplebucket')
callback = Aliyun::OSS::Callback.new(
url: 'http://oss-demo.aliyuncs.com:23450',
query: {user: 'put_object'},
body: 'bucket=${bucket}&object=${object}'
)
begin
bucket.put_object('files/hello', file: '/tmp/x', callback: callback)
rescue Aliyun::OSS::CallbackError => e
puts "Callback failed: #{e.message}"
end</details>
API reference
To call the OSS API directly (for example, when you need finer control over request signing), see Callback.
What's next
For common callback errors and how to resolve them, see How do I troubleshoot upload callback errors?
To set up server-side signatures, configure upload callbacks, and let clients upload directly to OSS via form upload, see Add signatures on the server, configure upload callbacks, and directly transfer data.
To configure upload callbacks for mobile apps, see Set up upload callbacks for mobile apps.