You need to enable JavaScript to run this app.
导航
上传回调(.NET SDK)
最近更新时间:2024.05.23 15:02:09首次发布时间:2024.05.23 15:02:09

上传回调是指客户端在请求时携带回调(Callback)参数,服务端在上传完成后,发送同步的 POST 回调请求到 CallBack 中指定的第三方应用服务器,在服务器确认接受并返回结果后,才将所有结果返回给客户端。
关于上传回调的详细介绍,请参见上传回调

示例代码

普通上传实现上传回调

using System;
using System.IO;
using System.Text;
using TOS;
using TOS.Error;
using TOS.Model;

namespace TestTos
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            var ak = Environment.GetEnvironmentVariable("TOS_ACCESS_KEY");
            var sk = Environment.GetEnvironmentVariable("TOS_SECRET_KEY");
            // endpoint 若没有指定HTTP协议(HTTP/HTTPS),默认使用 HTTPS
            // Bucket 的 Endpoint,以华北2(北京)为例:https://tos-cn-beijing.volces.com
            var endpoint = "https://tos-cn-beijing.volces.com";
            var region = "cn-beijing";
            // 填写 BucketName
            var bucketName = "*** Provide your bucket name ***";
            // 上传对象 Body,以 string 对象为例
            var objectContent = "Hello TOS";
            // 将文件上传到 example_dir 目录下的 example.txt 文件
            var objectKey = "example_dir/example.txt";
            // 上传回调参数
            var callback = "your callback param";
            // 上传回调自定义变量
            var callbackVar = "your callback custom variable";
            
            // 创建TOSClient实例
            var client = TosClientBuilder.Builder().SetAk(ak).SetSk(sk).SetEndpoint(endpoint).SetRegion(region).Build();

            try
            {
                byte[] binaryData = Encoding.UTF8.GetBytes(objectContent);
                using (MemoryStream requestContent = new MemoryStream(binaryData))
                {
                    // 创建上传文件输入
                    var putObjectInput = new PutObjectInput()
                    {
                        Bucket = bucketName,
                        Key = objectKey,
                        Content = requestContent,
                        Callback = Convert.ToBase64String(Encoding.UTF8.GetBytes(callback)),
                        CallbackVar = Convert.ToBase64String(Encoding.UTF8.GetBytes(callbackVar))
                    };
                    // 将字符串 “Hello TOS” 上传到指定 example_dir 目录下的 example.txt
                    var putObjectOutput = client.PutObject(putObjectInput);
                    Console.WriteLine("Put object succeeded, ETag: {0} ", putObjectOutput.ETag);
                    Console.WriteLine("Put object succeeded, CallbackResult: {0} ", putObjectOutput.CallbackResult);
                }
            }
            catch (TosServerException ex)
            {
                Console.WriteLine("Put object failed, request id {0}", ex.RequestID);
                Console.WriteLine("Put object failed, status code {0}", ex.StatusCode);
                Console.WriteLine("Put object failed, response error code {0}", ex.Code);
                Console.WriteLine("Put object failed, response error message {0}", ex.Message);
            }
            catch (TosClientException ex)
            {
                Console.WriteLine("Put object failed, error message {0}", ex.Message);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Put object failed, {0}", ex.Message);
            }
        }
    }
}

分片上传实现上传回调

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using TOS;
using TOS.Error;
using TOS.Model;

namespace ConsoleApp
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            var ak = Environment.GetEnvironmentVariable("TOS_ACCESS_KEY");
            var sk = Environment.GetEnvironmentVariable("TOS_SECRET_KEY");
            // endpoint 若没有指定HTTP协议(HTTP/HTTPS),默认使用 HTTPS
            // Bucket 的 Endpoint,以华北2(北京)为例:https://tos-cn-beijing.volces.com
            var endpoint = "https://tos-cn-beijing.volces.com";
            var region = "cn-beijing";
            // 填写 BucketName
            var bucketName = "*** Provide your bucket name ***";
            // 将文件上传到 example_dir 目录下的 example.txt 文件
            var objectKey = "example_dir/example.txt";
            // 需要上传的本地文件
            var localFileName = "/usr/local/test.txt";
            // 上传回调参数
            var callback = "your callback param";
            // 上传回调自定义变量
            var callbackVar = "your callback custom variable";

            // 创建TOSClient实例
            var client = TosClientBuilder.Builder().SetAk(ak).SetSk(sk).SetEndpoint(endpoint).SetRegion(region).Build();

            // 初始化分片,指定对象权限为私有,存储类型为低频并设置元数据信息
            var uploadID = "";
            try
            {
                var createMultipartUploadInput = new CreateMultipartUploadInput
                {
                    Bucket = bucketName,
                    Key = objectKey,
                    ACL = ACLType.ACLPrivate,
                    StorageClass = StorageClassType.StorageClassIa,
                    Meta = new Dictionary<string, string> { { "key", "value" } }
                };
                var createMultipartUploadOutput = client.CreateMultipartUpload(createMultipartUploadInput);
                uploadID = createMultipartUploadOutput.UploadID;
                Console.WriteLine("CreateMultipartUpload succeeded, request id {0}",
                    createMultipartUploadOutput.RequestID);
                Console.WriteLine("CreateMultipartUpload succeeded, upload id {0}", uploadID);
            }
            catch (TosServerException ex)
            {
                Console.WriteLine("CreateMultipartUpload failed, request id {0}", ex.RequestID);
                Console.WriteLine("CreateMultipartUpload failed, status code {0}", ex.StatusCode);
                Console.WriteLine("CreateMultipartUpload failed, response error code {0}", ex.Code);
                Console.WriteLine("CreateMultipartUpload failed, response error message {0}", ex.Message);
            }
            catch (TosClientException ex)
            {
                Console.WriteLine("CreateMultipartUpload failed, error message {0}", ex.Message);
            }
            catch (Exception ex)
            {
                Console.WriteLine("CreateMultipartUpload failed, {0}", ex.Message);
            }

            // part size 大小设置为 20M
            long partSize = 20 * 1024 * 1024;
            // 计算分片信息
            var fi = new FileInfo(localFileName);
            var fileSize = fi.Length;
            var partCount = fileSize / partSize;
            if (fileSize % partSize != 0) partCount++;
            var parts = new UploadedPart[partCount];

            // 开始分片上传
            try
            {
                using (var fileStream = File.Open(localFileName, FileMode.Open, FileAccess.Read))
                {
                    for (var i = 0; i < partCount; i++)
                    {
                        var offset = partSize * i;
                        // 定位到本次上传的起始位置。
                        fileStream.Seek(offset, 0);
                        // 计算本次上传的分片大小,最后一片为剩余的数据大小。
                        var contentSize = partSize < fileSize - offset ? partSize : fileSize - offset;
                        var UploadPartInput = new UploadPartInput
                        {
                            Bucket = bucketName,
                            Key = objectKey,
                            UploadID = uploadID,
                            // partNumber 编号从 1 开始
                            PartNumber = i + 1,
                            Content = fileStream,
                            ContentLength = contentSize
                        };
                        var uploadPartOutput = client.UploadPart(UploadPartInput);
                        parts[i] = new UploadedPart { PartNumber = i + 1, ETag = uploadPartOutput.ETag };
                        Console.WriteLine("UploadPart succeeded, request id {0}", uploadPartOutput.RequestID);
                    }
                }
            }
            catch (TosServerException ex)
            {
                Console.WriteLine("UploadPart failed, request id {0}", ex.RequestID);
                Console.WriteLine("UploadPart failed, status code {0}", ex.StatusCode);
                Console.WriteLine("UploadPart failed, response error code {0}", ex.Code);
                Console.WriteLine("UploadPart failed, response error message {0}", ex.Message);
            }
            catch (TosClientException ex)
            {
                Console.WriteLine("UploadPart failed, error message {0}", ex.Message);
            }
            catch (Exception ex)
            {
                Console.WriteLine("UploadPart failed, {0}", ex.Message);
            }

            // 合并分片
            try
            {
                var completeMultipartUploadInput = new CompleteMultipartUploadInput
                {
                    Bucket = bucketName,
                    Key = objectKey,
                    UploadID = uploadID,
                    Parts = parts,
                    Callback = Convert.ToBase64String(Encoding.UTF8.GetBytes(callback)),
                    CallbackVar = Convert.ToBase64String(Encoding.UTF8.GetBytes(callbackVar))
                };
                var completeMultipartUploadOutput = client.CompleteMultipartUpload(completeMultipartUploadInput);
                Console.WriteLine("CompleteMultipartUpload succeeded, request id {0}", completeMultipartUploadOutput.RequestID);
                Console.WriteLine("CompleteMultipartUpload succeeded, callback result {0}", completeMultipartUploadOutput.CallbackResult);
            }
            catch (TosServerException ex)
            {
                Console.WriteLine("CompleteMultipartUpload failed, request id {0}", ex.RequestID);
                Console.WriteLine("CompleteMultipartUpload failed, status code {0}", ex.StatusCode);
                Console.WriteLine("CompleteMultipartUpload failed, response error code {0}", ex.Code);
                Console.WriteLine("CompleteMultipartUpload failed, response error message {0}", ex.Message);
            }
            catch (TosClientException ex)
            {
                Console.WriteLine("CompleteMultipartUpload failed, error message {0}", ex.Message);
            }
            catch (Exception ex)
            {
                Console.WriteLine("CompleteMultipartUpload failed, {0}", ex.Message);
            }
        }
    }
}