This topic describes how to use upload callback.

For the complete code used to implement upload callback, visit GitHub. For more information about upload callback, see Callback.

The following code provides an example on how to use upload callback:

// This example uses the endpoint of the China (Hangzhou) region. Specify the actual endpoint based on your requirements.
String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
// Security risks may arise if you use the AccessKey pair of an Alibaba Cloud account to log on to OSS, because the account has permissions on all API operations. We recommend that you use your RAM user's credentials to call API operations or perform routine operations and maintenance. To create a RAM user, log on to https://ram.console.aliyun.com.
String accessKeyId = "<yourAccessKeyId>";
String accessKeySecret = "<yourAccessKeySecret>";
String bucketName = "<yourBucketName>";
String objectName = "<yourObjectName>";
// Specify the IP address of the server to which you want send the callback request, for example, http://oss-demo.aliyuncs.com:23450 or http://127.0.0.1:9090.
String callbackUrl = "<yourCallbackServerUrl>";

// Create an OSSClient instance.
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

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) Configure the value of the host field carried in the callback request header. This value is the same as the value of the host field specified for your server.
// callback.setCallbackHost("yourCallbackHost");
// Configure the value of the body field carried in the callback request.
callback.setCallbackBody("{\\\"mimeType\\\":${mimeType},\\\"size\\\":${size}}");
// Configure Content-Type for the callback request.
callback.setCalbackBodyType(CalbackBodyType.JSON);
// 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);

PutObjectResult putObjectResult = ossClient.putObject(putObjectRequest);

// Read the response for the upload callback request.
byte[] buffer = new byte[1024];
putObjectResult.getResponse().getContent().read(buffer);
// If you do not close the reader after the data is read, connection leaks may occur. Consequently, no available connections are left and an exception occurs.
putObjectResult.getResponse().getContent().close();

// Shut down the OSSClient.
ossClient.shutdown();
		

For more information about upload callback, see upload callback in Developer Guide.