开发者社区> 问答> 正文

.NET-SDK之如何实现下载文件(二)?


只获取文件元信息


通过GetObjectMetadata方法可以只获取ObjectMeta而不获取文件的实体。代码如下:

  1. // 初始化OssClient
  2. var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
  3. /// <summary>
  4. /// 获取文件的元信息。
  5. /// </summary>
  6. /// <param name="bucketName">存储空间的名称</param>
  7. /// <param name="key">文件在OSS上的名称</param>
  8. public void GetObjectMetadata(string bucketName, string key)
  9. {
  10.     try
  11.     {
  12.         var metadata = client.GetObjectMetadata(bucketName, key);
  13.         Console.WriteLine("Get object meta succeeded");  
  14.         Console.WriteLine("Content-Type:{0}", metadata.ContentType);
  15.         Console.WriteLine("Cache-Control:{0}", metadata.CacheControl);
  16.     }
  17.     catch (Exception ex)
  18.     {
  19.         Console.WriteLine("Get object meta failed. {0}", ex.Message);
  20.     }
  21. }


进度条


OSS .Net SDK支持进度条功能,指示上传、下载的进度。下面的代码以 GetObject 为例,说明进度条功能的使用方法。
  1. using Aliyun.OSS;
  2. var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
  3. public static void GetObjectProgress(string bucketName)
  4. {
  5.     const string key = "GetObjectProgress";
  6.     try
  7.     {
  8.         client.PutObject(bucketName, key, fileToUpload);
  9.         var getObjectRequest = new GetObjectRequest(bucketName, key);
  10.         getObjectRequest.StreamTransferProgress += streamProgressCallback;
  11.         var ossObject = client.GetObject(getObjectRequest);
  12.         using (var stream = ossObject.Content)
  13.         {
  14.             var buffer = new byte[1024 * 1024];
  15.             var bytesRead = 0;
  16.             while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
  17.             {
  18.                 // 处理读出的数据
  19.             }                    
  20.         }
  21.         Console.WriteLine("Get object:{0} succeeded", key);
  22.     }
  23.     catch (OssException ex)
  24.     {
  25.         Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
  26.             ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
  27.     }
  28.     catch (Exception ex)
  29.     {
  30.         Console.WriteLine("Failed with error info: {0}", ex.Message);
  31.     }
  32. }
  33. private static void streamProgressCallback(object sender, StreamTransferProgressArgs args)
  34. {
  35.     System.Console.WriteLine("ProgressCallback - TotalBytes:{0}, TransferredBytes:{1}",
  36.         args.TotalBytes, args.TransferredBytes);
  37. }

提示:
  • PutObject、AppendObject、UploadPart、ResumableUploadObject、GetObject都支持进度功能,完整代码请参考:GitHub

展开
收起
青衫无名 2017-10-18 15:11:19 1811 0
0 条回答
写回答
取消 提交回答
问答排行榜
最热
最新

相关电子书

更多
从 SDK 到编解码:视频直播架构解析 立即下载
跨平台的云服务SDK需要什么 立即下载
一个跨平台的云服务SDK需要什么 立即下载