对象存储OSS在完成文件(Object)上传时可以提供回调(Callback)给应用服务器。您只需要在发送给OSS的请求中携带相应的Callback参数,即可实现回调。
注意事项
示例代码
以下代码用于上传回调:
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()
{
// 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// 填写Bucket名称,例如examplebucket。
var bucketName = "examplebucket";
// 填写Object完整路径。Object完整路径中不能包含Bucket名称,例如exampledir/exampleobject.txt。
var objectName = "exampledir/exampleobject.txt";
// 填写本地文件的完整路径,例如D:\\localpath\\examplefile.txt。如果未指定本地路径,则默认从示例程序所属项目对应本地路径中上传文件。
var localFilename = "D:\\localpath\\examplefile.txt";
// 设置回调服务器地址,例如https://example.com:23450。
const string callbackUrl = "yourCallbackServerUrl";
// 设置发起回调时请求body的值。
const string callbackBody = "bucket=${bucket}&object=${object}&etag=${etag}&size=${size}&mimeType=${mimeType}&" +
"my_var1=${x:var1}&my_var2=${x:var2}";
// 创建OssClient实例。
var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
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);
}
}
// 设置上传回调。
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;
}
// 读取上传回调返回的消息内容。
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;
}
}
}