如果您只需获取对象中的部分数据,您可以使用范围下载,下载指定范围内的数据,本文介绍范围下载。
以下代码用于下载桶中对象的 32-64 字节数据。
using System; using System.IO; 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 ***"; // 下载对象 var objectKey = "example_dir/example.txt"; // 创建TOSClient实例 var client = TosClientBuilder.Builder().SetAk(ak).SetSk(sk).SetEndpoint(endpoint).SetRegion(region).Build(); try { var getObjectInput = new GetObjectInput() { Bucket = bucketName, Key = objectKey, // 获取 32-64 字节,包含 32 和 64 共 33 字节 RangeStart = 32, RangeEnd = 64 }; var getObjectOutput = client.GetObject(getObjectInput); Console.WriteLine("GetObject succeeded, request id {0}", getObjectOutput.RequestID); // 下载时前设置的 response content type Console.WriteLine("GetObject succeeded, content type {0}", getObjectOutput.ContentType); // 下载时前设置的 response content encoding Console.WriteLine("GetObject succeeded, content encoding {0}", getObjectOutput.ContentEncoding); // 下载数据大小 Console.WriteLine("GetObject succeeded, content length {0}", getObjectOutput.ContentLength); // 完成下载 using (var reader = new StreamReader(getObjectOutput.Content)) { Console.WriteLine("GetObject failed, content {0}", reader.ReadToEnd()); getObjectOutput.Content.Close(); } } catch (TosServerException ex) { Console.WriteLine("GetObject failed, request id {0}", ex.RequestID); Console.WriteLine("GetObject failed, status code {0}", ex.StatusCode); Console.WriteLine("GetObject failed, response error code {0}", ex.Code); Console.WriteLine("GetObject failed, response error message {0}", ex.Message); } catch (TosClientException ex) { Console.WriteLine("GetObject failed, error message {0}", ex.Message); } catch (Exception ex) { Console.WriteLine("GetObject failed, {0}", ex.Message); } } } }
关于范围下载的 API 接口详细介绍,请参见 GetObject。