简介
本文介绍对象存储 COS 通过.NET(C#) SDK 实现上传对象功能的示例代码和描述。包括高级接口、简单接口、分块上传三个部分。
注意事项
若您使用简单上传,需要具有目标对象的写权限:在您进行 授权策略 时,action 需要设置为
cos:PutObject
,更多授权请参见 支持CAM的业务接口。若您使用高级接口的自动分块上传或使用简单接口实现分块上传,需要具有目标对象的初始化分块上传、上传分块、完成分块上传的权限:在您进行 授权策略 时,action 需要设置为
cos:InitiateMultipartUpload
,cos:UploadPart
,cos:CompleteMultipartUpload
,更多授权请参见 支持CAM的业务接口。若您使用高级接口的断点续传,需要具有目标对象的初始化分块上传、上传分块、完成分块上传、列举分块上传任务、列举已上传分块的权限:在您进行 授权策略 时,action 需要设置为
cos:InitiateMultipartUpload
,cos:UploadPart
,cos:CompleteMultipartUpload
,cos:ListMultipartUploads
,cos:ListParts
更多授权请参见 支持CAM的业务接口。相关示例
功能名称 | 描述 | 示例代码 |
高级接口 | 高级接口封装了简单上传、分块上传接口,根据文件大小智能的选择上传方式,同时支持断点续传功能。 | |
简单接口 | PUT Object 接口可以上传一个对象至指定存储桶中,不支持自动分块上传和断点续传。最大支持上传不超过5GB的对象,5GB以上对象请使用 分块上传 或 高级接口 上传。 | |
分块操作 | 分块上传可以实现将前期准备整个对象切分为多个分块,然后再将这些分块上传到对象存储(Cloud Object Storage,COS)。 |
前期准备:初始化 COS 服务实例
public class UploadObject { private CosXml cosXml; //将服务用户设置成数据成员 // 初始化COS服务实例 private void InitCosXml() { string region = Environment.GetEnvironmentVariable("COS_REGION"); CosXmlConfig config = new CosXmlConfig.Builder() .SetRegion(region) // 设置默认的地域, COS 地域的简称请参照 https://cloud.tencent.com/document/product/436/6224 .Build(); string secretId = Environment.GetEnvironmentVariable("SECRET_ID"); // 云 API 密钥 SecretId, 获取 API 密钥请参照 https://console.cloud.tencent.com/cam/capi string secretKey = Environment.GetEnvironmentVariable("SECRET_KEY"); // 云 API 密钥 SecretKey, 获取 API 密钥请参照 https://console.cloud.tencent.com/cam/capi long durationSecond = 600; //每次请求签名有效时长,单位为秒 QCloudCredentialProvider qCloudCredentialProvider = new DefaultQCloudCredentialProvider(secretId, secretKey, durationSecond); this.cosXml = new CosXmlServer(config, qCloudCredentialProvider); } }
高级接口(推荐)
高级接口封装了简单上传、分块上传接口,根据文件大小智能的选择上传方式,同时支持续传功能。
注意:
文件大小小于分块阈值时选择简单上传,超过阈值时使用分块上传,阈值支持用户自行配置,默认为5MB。
分块大小支持用户自行配置,默认为1MB。
针对.NET Framework 4.0 及以下的用户,高级接口暂不可用,详见 向下兼容指南。
高级接口上传本地文件
public async Task TransferUploadFile() { TransferConfig transferConfig = new TransferConfig(); // 手动设置开始分块上传的大小阈值为10MB,默认值为5MB transferConfig.DivisionForUpload = 10 * 1024 * 1024; // 手动设置分块上传中每个分块的大小为2MB,默认值为1MB transferConfig.SliceSizeForUpload = 2 * 1024 * 1024; // 初始化 TransferManager TransferManager transferManager = new TransferManager(cosXml, transferConfig); // 存储桶名称,此处填入格式必须为 BucketName-APPID, 其中 APPID 获取参考 https://console.cloud.tencent.com/developer String bucket = "examplebucket-1250000000"; String cosPath = "exampleobject"; //对象在存储桶中的位置标识符,即称对象键 String srcPath = "temp-source-file";//本地文件绝对路径 // 上传对象 COSXMLUploadTask uploadTask = new COSXMLUploadTask(bucket, cosPath); uploadTask.SetSrcPath(srcPath); uploadTask.progressCallback = delegate (long completed, long total) { Console.WriteLine(String.Format("progress = {0:##.##}%", completed * 100.0 / total)); }; //开始上传 try { COSXMLUploadTask.UploadTaskResult result = await transferManager.UploadAsync(uploadTask); Console.WriteLine(result.GetResultInfo()); } catch (Exception e) { Console.WriteLine("CosException: " + e); } }public static void Main() { UploadObject domo = new UploadObject(); //初始化COS服务 domo.InitCosXml(); //高级上传 domo.TransferUploadFile().Wait(); }
对于上传任务,可以通过以下方式暂停:
uploadTask.Pause();
暂停之后,可以通过以下方式续传:
uploadTask.Resume();
也通过以下方式取消上传:
uploadTask.Cancel();
批量上传
public void BatchUpload() { TransferConfig transferConfig = new TransferConfig(); // 初始化 TransferManager TransferManager transferManager = new TransferManager(cosXml, transferConfig); // 存储桶名称,此处填入格式必须为 bucketname-APPID, 其中 APPID 获取参考 https://console.cloud.tencent.com/developer string bucket = "examplebucket-1250000000"; for (int i = 0; i < 5; i++) { // 上传对象 string cosPath = "exampleobject" + i; //对象在存储桶中的位置标识符,即称对象键 string srcPath = @"temp-source-file";//本地文件绝对路径 COSXMLUploadTask uploadTask = new COSXMLUploadTask(bucket, cosPath); uploadTask.SetSrcPath(srcPath); transferManager.UploadAsync(uploadTask).Wait(); } }
简单接口
注意:
Key(文件名)不能以
/
结尾,否则会被识别为文件夹。每个主账号(即同一个 APPID),存储桶的 ACL 规则数量最多为1000条,对象 ACL 规则数量不限制。如果您不需要进行对象 ACL 控制,请在上传时不要设置,默认继承存储桶权限。
上传本地文件
public void PutObject() { try { // 存储桶名称,此处填入格式必须为 bucketname-APPID, 其中 APPID 获取参考 https://console.cloud.tencent.com/developer string bucket = "examplebucket-1250000000"; string key = "exampleobject"; //对象键 string srcPath = @"temp-source-file";//本地文件绝对路径 PutObjectRequest request = new PutObjectRequest(bucket, key, srcPath); //设置进度回调 request.SetCosProgressCallback(delegate (long completed, long total) { Console.WriteLine(String.Format("progress = {0:##.##}%", completed * 100.0 / total)); }); PutObjectResult result = cosXml.PutObject(request); //打印返回结果 Console.WriteLine(result.GetResultInfo()); } catch (COSXML.CosException.CosClientException clientEx) { Console.WriteLine("CosClientException: " + clientEx); } catch (COSXML.CosException.CosServerException serverEx) { Console.WriteLine("CosServerException: " + serverEx.GetInfo()); } }
表单上传对象
public void PostObject() { try { // 存储桶名称,此处填入格式必须为 bucketname-APPID, 其中 APPID 获取参考 https://console.cloud.tencent.com/developer string bucket = "examplebucket-1250000000"; string key = "exampleobject"; //对象键 string srcPath = @"temp-source-file";//本地文件绝对路径 PostObjectRequest request = new PostObjectRequest(bucket, key, srcPath); //设置进度回调 request.SetCosProgressCallback(delegate (long completed, long total) { Console.WriteLine(String.Format("progress = {0:##.##}%", completed * 100.0 / total)); }); //执行请求 PostObjectResult result = cosXml.PostObject(request); //请求成功 Console.WriteLine(result.GetResultInfo()); } catch (COSXML.CosException.CosClientException clientEx) { Console.WriteLine("CosClientException: " + clientEx); } catch (COSXML.CosException.CosServerException serverEx) { Console.WriteLine("CosServerException: " + serverEx.GetInfo()); } }
上传二进制数据
public void UploadBytes() { try { // 存储桶名称,此处填入格式必须为 bucketname-APPID, 其中 APPID 获取参考 https://console.cloud.tencent.com/developer string bucket = "examplebucket-1250000000"; string cosPath = "exampleObject"; // 对象键 byte[] data = new byte[1024]; // 二进制数据 PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, cosPath, data); // 发起上传 PutObjectResult result = cosXml.PutObject(putObjectRequest); Console.WriteLine(result.GetResultInfo()); } catch (COSXML.CosException.CosClientException clientEx) { //请求失败 Console.WriteLine("CosClientException: " + clientEx); } catch (COSXML.CosException.CosServerException serverEx) { //请求失败 Console.WriteLine("CosServerException: " + serverEx.GetInfo()); } }
从文件流上传
// 文件流上传, 从 5.4.24 版本开始支持 public void PutObjectStream() { try { // 存储桶名称,此处填入格式必须为 bucketname-APPID, 其中 APPID 获取参考 https://console.cloud.tencent.com/developer string bucket = "examplebucket-1250000000"; string key = "exampleobject"; //对象键 string srcPath = @"temp-source-file";//本地文件绝对路径 // 打开只读的文件流对象 FileStream fileStream = new FileStream(srcPath, FileMode.Open, FileAccess.Read); // 组装上传请求,其中 offset sendLength 为可选参数 long offset = 0L; long sendLength = fileStream.Length; PutObjectRequest request = new PutObjectRequest(bucket, key, fileStream, offset, sendLength); //设置进度回调 request.SetCosProgressCallback(delegate (long completed, long total) { Console.WriteLine(String.Format("progress = {0:##.##}%", completed * 100.0 / total)); }); //执行请求 PutObjectResult result = cosXml.PutObject(request); //关闭文件流 fileStream.Close(); //打印请求结果 Console.WriteLine(result.GetResultInfo()); } catch (COSXML.CosException.CosClientException clientEx) { Console.WriteLine("CosClientException: " + clientEx); } catch (COSXML.CosException.CosServerException serverEx) { Console.WriteLine("CosServerException: " + serverEx.GetInfo()); } }
创建目录
public void CreateDir() { try { // 存储桶名称,此处填入格式必须为 bucketname-APPID, 其中 APPID 获取参考 https://console.cloud.tencent.com/developer string bucket = "examplebucket-1250000000"; string cosPath = "dir/"; // 对象键 PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, cosPath, new byte[0]); PutObjectResult result = cosXml.PutObject(putObjectRequest); Console.WriteLine(result.GetResultInfo()); } catch (COSXML.CosException.CosClientException clientEx) { Console.WriteLine("CosClientException: " + clientEx); } catch (COSXML.CosException.CosServerException serverEx) { Console.WriteLine("CosServerException: " + serverEx.GetInfo()); } }
分块上传
分块上传的流程
1. 初始化分块上传(Initiate Multipart Upload),得到 UploadId。
2. 使用 UploadId 上传分块(Upload Part)。
3. 完成分块上传(Complete Multipart Upload)。
分块继续上传的流程
1. 如果没有记录 UploadId,查询分块上传任务(List Multipart Uploads),得到对应文件的 UploadId。
2. 使用 UploadId 列出已上传的分块(List Parts)。
3. 使用 UploadId 上传剩余的分块(Upload Part)。
4. 完成分块上传(Complete Multipart Upload)。
终止分块上传的流程
1. 如果没有记录 UploadId,查询分块上传任务(List Multipart Uploads),得到对应文件的 UploadId。
2. 终止分块上传并删除已上传分块(Abort Multipart Upload)。
初始化分块上传
public void InitiateMultipartUpload() { try { string bucket = "examplebucket-1250000000"; string key = "exampleobject"; //对象键 InitMultipartUploadRequest request = new InitMultipartUploadRequest(bucket, key); //执行请求 InitMultipartUploadResult result = cosXml.InitMultipartUpload(request); //请求成功 this.uploadId = result.initMultipartUpload.uploadId; //用于后续分块上传的 uploadId Console.WriteLine(result.GetResultInfo()); } catch (COSXML.CosException.CosClientException clientEx) { Console.WriteLine("CosClientException: " + clientEx); } catch (COSXML.CosException.CosServerException serverEx) { Console.WriteLine("CosServerException: " + serverEx.GetInfo()); } }
查询正在进行的分块上传任务
public void ListMultipartUploads() { try { // 存储桶名称,此处填入格式必须为 bucketname-APPID, 其中 APPID 获取参考 https://console.cloud.tencent.com/developer string bucket = "examplebucket-1250000000"; ListMultiUploadsRequest request = new ListMultiUploadsRequest(bucket); //执行请求 ListMultiUploadsResult result = cosXml.ListMultiUploads(request); //请求成功 Console.WriteLine(result.GetResultInfo()); } catch (COSXML.CosException.CosClientException clientEx) { Console.WriteLine("CosClientException: " + clientEx); } catch (COSXML.CosException.CosServerException serverEx) { Console.WriteLine("CosServerException: " + serverEx.GetInfo()); } }
上传文件分块
public void UploadPart() { try { // 存储桶名称,此处填入格式必须为 bucketname-APPID, 其中 APPID 获取参考 https://console.cloud.tencent.com/developer string bucket = "examplebucket-1250000000"; string key = "exampleobject"; //对象键 string uploadId = "exampleUploadId"; //初始化分块上传返回的uploadId int partNumber = 1; //分块编号,必须从1开始递增 string srcPath = @"temp-source-file";//本地文件绝对路径 UploadPartRequest request = new UploadPartRequest(bucket, key, partNumber, uploadId, srcPath, 0, -1); //设置进度回调 request.SetCosProgressCallback(delegate (long completed, long total) { Console.WriteLine(String.Format("progress = {0:##.##}%", completed * 100.0 / total)); }); //执行请求 UploadPartResult result = cosXml.UploadPart(request); //获取返回分块的eTag,用于后续CompleteMultiUploadsthis.eTag = result.eTag;//请求成功 Console.WriteLine(result.GetResultInfo()); } catch (COSXML.CosException.CosClientException clientEx) { Console.WriteLine("CosClientException: " + clientEx); } catch (COSXML.CosException.CosServerException serverEx) { Console.WriteLine("CosServerException: " + serverEx.GetInfo()); } }
查询已上传的分块
public void ListParts() { try { // 存储桶名称,此处填入格式必须为 bucketname-APPID, 其中 APPID 获取参考 https://console.cloud.tencent.com/developer string bucket = "examplebucket-1250000000"; string key = "exampleobject"; //对象键 string uploadId = "exampleUploadId"; //初始化分块上传返回的uploadId ListPartsRequest request = new ListPartsRequest(bucket, key, uploadId); //执行请求 ListPartsResult result = cosXml.ListParts(request); //请求成功 //列举已上传的分块 List<COSXML.Model.Tag.ListParts.Part> alreadyUploadParts = result.listParts.parts; Console.WriteLine(result.GetResultInfo()); } catch (COSXML.CosException.CosClientException clientEx) { Console.WriteLine("CosClientException: " + clientEx); } catch (COSXML.CosException.CosServerException serverEx) { Console.WriteLine("CosServerException: " + serverEx.GetInfo()); } }
完成分块上传
public void CompleteMultipartUpload() { try { // 存储桶名称,此处填入格式必须为 bucketname-APPID, 其中 APPID 获取参考 https://console.cloud.tencent.com/developer string bucket = "examplebucket-1250000000"; string key = "exampleobject"; //对象键 string uploadId = "exampleUploadId"; //初始化分块上传返回的uploadId CompleteMultipartUploadRequest request = new CompleteMultipartUploadRequest(bucket, key, uploadId); //设置已上传的parts,必须有序,按照partNumber递增 request.SetPartNumberAndETag(1, this.eTag); //执行请求 CompleteMultipartUploadResult result = cosXml.CompleteMultiUpload(request); //请求成功 Console.WriteLine(result.GetResultInfo()); } catch (COSXML.CosException.CosClientException clientEx) { Console.WriteLine("CosClientException: " + clientEx); } catch (COSXML.CosException.CosServerException serverEx) { Console.WriteLine("CosServerException: " + serverEx.GetInfo()); } }
终止分块上传任务
public void AbortMultipartUpload() { try { // 存储桶名称,此处填入格式必须为 bucketname-APPID, 其中 APPID 获取参考 https://console.cloud.tencent.com/developer string bucket = "examplebucket-1250000000"; string key = "exampleobject"; //对象键 string uploadId = "exampleUploadId"; //初始化分块上传返回的uploadId AbortMultipartUploadRequest request = new AbortMultipartUploadRequest(bucket, key, uploadId); //执行请求 AbortMultipartUploadResult result = cosXml.AbortMultiUpload(request); //请求成功 Console.WriteLine(result.GetResultInfo()); } catch (COSXML.CosException.CosClientException clientEx) { Console.WriteLine("CosClientException: " + clientEx); } catch (COSXML.CosException.CosServerException serverEx) { Console.WriteLine("CosServerException: " + serverEx.GetInfo()); } }
API 操作
关于简单操作的 API 接口说明,请参见 PUT Object 、POST Object 文档。
关于分块操作的 API 接口说明,请参见 List Multipart Uploads 、Initiate Multipart Upload 、Upload Part 、List Parts、Abort Multipart Upload、Complete Multipart Upload文档。