追加上传指使用 AppendObject 接口在已存在的对象数据末尾追加写入新数据。追加上传创建的对象类型为追加类型(Appendable Object),可在对象末尾追加写入数据。普通上传和分片上传创建的对象类型为普通类型(Normal Object),无法追加写入数据。
使用 AppendObject 接口时,对象的大小限制说明如下:
以下代码用于先将指定字符流追加上传到指定文件,再将指定路径下的本地文件追加上传到同一个文件。
using System; 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 ***"; // 上传对象 Body,以 string 对象为例 var objectContent = "your append object value"; // 将文件上传到 example_dir 目录下的 example.txt 文件 var objectKey = "example_dir/example.txt"; // 需要上传的本地文件 var localFileName = "/usr/local/test.txt"; // 创建TOSClient实例 var client = TosClientBuilder.Builder().SetAk(ak).SetSk(sk).SetEndpoint(endpoint).SetRegion(region).Build(); try { var binaryData = Encoding.UTF8.GetBytes(objectContent); AppendObjectOutput appendObjectOutput; // 通过字符串追加上传对象 using (var requestContent = new MemoryStream(binaryData)) { // 创建追加上传文件输入 var appendObjectInput = new AppendObjectInput { Bucket = bucketName, Key = objectKey, Content = requestContent }; // 上传字符流 appendObjectOutput = client.AppendObject(appendObjectInput); Console.WriteLine("Append object succeeded, request id: {0} ", appendObjectOutput.RequestID); } // 从文件流中获取数据 using (var fileStream = File.OpenRead(localFileName)) { // 创建追加上传文件输入 var appendObjectInput = new AppendObjectInput { Bucket = bucketName, Key = objectKey, // 指定下次 append offset Offset = appendObjectOutput.NextAppendOffset, Content = fileStream }; // 上传文件流 appendObjectOutput = client.AppendObject(appendObjectInput); Console.WriteLine("Append object succeeded, request id: {0} ", appendObjectOutput.RequestID); } } 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); } } } }