终端一体化运控平台
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

OSS_Helper.cs 11 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using Aliyun.OSS;
  8. using Aliyun.OSS.Common;
  9. namespace BPASmartClient.IoT.Model
  10. {
  11. public class OSS_Helper
  12. {
  13. const string accessKeyId = "xxx";
  14. const string accessKeySecret = "xxx";
  15. const string endpoint = "http://oss-cn-shanghai.aliyuncs.com";
  16. const string bucketName = "xxx";
  17. OssClient client = null;
  18. public OSS_Helper()
  19. {
  20. // 由用户指定的OSS访问地址、阿里云颁发的AccessKeyId/AccessKeySecret构造一个新的OssClient实例。
  21. client = new OssClient(endpoint, accessKeyId, accessKeySecret);
  22. }
  23. /*简单上传:文件最大不能超过5GB。
  24. 追加上传:文件最大不能超过5GB。
  25. 断点续传上传:支持并发、断点续传、自定义分片大小。大文件上传推荐使用断点续传。最大不能超过48.8TB。
  26. 分片上传:当文件较大时,可以使用分片上传,最大不能超过48.8TB。*/
  27. /// <summary>
  28. ///
  29. /// </summary>
  30. /// <param name="objectName"></param>
  31. /// <param name="localFilename"></param>
  32. public void Simple_Up(string objectName, string localFilename)
  33. {
  34. //var objectName = "Project/222.jpg";
  35. //var localFilename = @"C:\tiger.jpg";
  36. // 创建OssClient实例。
  37. try
  38. {
  39. // 上传文件。
  40. client.PutObject(bucketName, objectName, localFilename);
  41. Console.WriteLine("Put object succeeded");
  42. }
  43. catch (Exception ex)
  44. {
  45. Console.WriteLine("Put object failed, {0}", ex.Message);
  46. }
  47. }
  48. /// <summary>
  49. /// 分片上传
  50. /// </summary>
  51. /// <param name="objectName"></param>
  52. /// <param name="localFilename"></param>
  53. public void Multipar_tUp(string objectName, string localFilename)
  54. {
  55. var uploadId = "";
  56. try
  57. {
  58. // 定义上传文件的名字和所属存储空间。在InitiateMultipartUploadRequest中,可以设置ObjectMeta,但不必指定其中的ContentLength。
  59. var request = new InitiateMultipartUploadRequest(bucketName, objectName);
  60. var result = client.InitiateMultipartUpload(request);
  61. uploadId = result.UploadId;
  62. // 打印UploadId。
  63. Console.WriteLine("Init multi part upload succeeded");
  64. Console.WriteLine("Upload Id:{0}", result.UploadId);
  65. }
  66. catch (Exception ex)
  67. {
  68. throw ex;
  69. }
  70. // 计算分片总数。
  71. var partSize = 1024 * 1024;
  72. var fi = new FileInfo(localFilename);
  73. var fileSize = fi.Length;
  74. var partCount = fileSize / partSize;
  75. if (fileSize % partSize != 0)
  76. {
  77. partCount++;
  78. }
  79. // 开始分片上传。partETags是保存partETag的列表,OSS收到用户提交的分片列表后,会逐一验证每个分片数据的有效性。 当所有的数据分片通过验证后,OSS会将这些分片组合成一个完整的文件。
  80. var partETags = new List<PartETag>();
  81. try
  82. {
  83. using (var fs = File.Open(localFilename, FileMode.Open))
  84. {
  85. for (var i = 0; i < partCount; i++)
  86. {
  87. var skipBytes = (long)partSize * i;
  88. // 定位到本次上传起始位置。
  89. fs.Seek(skipBytes, 0);
  90. // 计算本次上传的片大小,最后一片为剩余的数据大小。
  91. var size = (partSize < fileSize - skipBytes) ? partSize : (fileSize - skipBytes);
  92. var request = new UploadPartRequest(bucketName, objectName, uploadId)
  93. {
  94. InputStream = fs,
  95. PartSize = size,
  96. PartNumber = i + 1
  97. };
  98. // 调用UploadPart接口执行上传功能,返回结果中包含了这个数据片的ETag值。
  99. var result = client.UploadPart(request);
  100. partETags.Add(result.PartETag);
  101. Console.WriteLine("finish {0}/{1}", partETags.Count, partCount);
  102. }
  103. Console.WriteLine("Put multi part upload succeeded");
  104. }
  105. }
  106. catch (Exception ex)
  107. {
  108. throw ex;
  109. }
  110. // 列举已上传的分片。
  111. try
  112. {
  113. var listPartsRequest = new ListPartsRequest(bucketName, objectName, uploadId);
  114. var listPartsResult = client.ListParts(listPartsRequest);
  115. Console.WriteLine("List parts succeeded");
  116. // 遍历所有分片。
  117. var parts = listPartsResult.Parts;
  118. foreach (var part in parts)
  119. {
  120. Console.WriteLine("partNumber: {0}, ETag: {1}, Size: {2}", part.PartNumber, part.ETag, part.Size);
  121. }
  122. }
  123. catch (Exception ex)
  124. {
  125. throw ex;
  126. }
  127. // 完成分片上传。
  128. try
  129. {
  130. var completeMultipartUploadRequest = new CompleteMultipartUploadRequest(bucketName, objectName, uploadId);
  131. foreach (var partETag in partETags)
  132. {
  133. completeMultipartUploadRequest.PartETags.Add(partETag);
  134. }
  135. var result = client.CompleteMultipartUpload(completeMultipartUploadRequest);
  136. Console.WriteLine("complete multi part succeeded");
  137. }
  138. catch (Exception ex)
  139. {
  140. throw ex;
  141. }
  142. }
  143. /// <summary>
  144. /// 上传
  145. /// </summary>
  146. /// <param name="objectName"></param>
  147. /// <param name="localFilename"></param>
  148. /// <param name="checkpointDir"></param>
  149. public void chkin_Up(string objectName, string localFilename, string checkpointDir)
  150. {
  151. try
  152. {
  153. // 通过UploadFileRequest设置多个参数。
  154. UploadObjectRequest request = new UploadObjectRequest(bucketName, objectName, localFilename)
  155. {
  156. // 指定上传的分片大小。
  157. PartSize = 1024 * 1024,
  158. // 指定并发线程数。
  159. ParallelThreadCount = 10,
  160. // checkpointDir保存断点续传的中间状态,用于失败后继续上传。如果checkpointDir为null,断点续传功能不会生效,每次失败后都会重新上传。
  161. CheckpointDir = checkpointDir,
  162. };
  163. // 断点续传上传。
  164. client.ResumableUploadObject(request);
  165. Console.WriteLine("Resumable upload object:{0} succeeded", objectName);
  166. }
  167. catch (OssException ex)
  168. {
  169. Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
  170. ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
  171. }
  172. catch (Exception ex)
  173. {
  174. Console.WriteLine("Failed with error info: {0}", ex.Message);
  175. }
  176. }
  177. /// <summary>
  178. /// 下载文件
  179. /// </summary>
  180. /// <param name="objectName"></param>
  181. /// <param name="downloadFilename"></param>
  182. public void Stream_Down(string objectName, string downloadFilename)
  183. {
  184. // objectName 表示您在下载文件时需要指定的文件名称,如abc/efg/123.jpg。
  185. //var objectName = "Project/cc.jpg";
  186. //var downloadFilename = @"D:\GG.jpg";
  187. // 创建OssClient实例。
  188. //var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
  189. try
  190. {
  191. // 下载文件到流。OssObject 包含了文件的各种信息,如文件所在的存储空间、文件名、元信息以及一个输入流。
  192. var obj = client.GetObject(bucketName, objectName);
  193. using (var requestStream = obj.Content)
  194. {
  195. byte[] buf = new byte[1024];
  196. var fs = File.Open(downloadFilename, FileMode.OpenOrCreate);
  197. var len = 0;
  198. // 通过输入流将文件的内容读取到文件或者内存中。
  199. while ((len = requestStream.Read(buf, 0, 1024)) != 0)
  200. {
  201. fs.Write(buf, 0, len);
  202. }
  203. fs.Close();
  204. }
  205. Console.WriteLine("Get object succeeded");
  206. }
  207. catch (Exception ex)
  208. {
  209. Console.WriteLine("Get object failed. {0}", ex.Message);
  210. }
  211. }
  212. public void DownPBar()
  213. {
  214. }
  215. public static void GetObjectProgress()
  216. {
  217. var endpoint = "<yourEndpoint>";
  218. var accessKeyId = "<yourAccessKeyId>";
  219. var accessKeySecret = "<yourAccessKeySecret>";
  220. var bucketName = "<yourBucketName>";
  221. var objectName = "<yourObjectName>";
  222. // 创建OssClient实例。
  223. var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
  224. try
  225. {
  226. var getObjectRequest = new GetObjectRequest(bucketName, objectName);
  227. getObjectRequest.StreamTransferProgress += streamProgressCallback;
  228. // 下载文件。
  229. var ossObject = client.GetObject(getObjectRequest);
  230. using (var stream = ossObject.Content)
  231. {
  232. var buffer = new byte[1024 * 1024];
  233. var bytesRead = 0;
  234. while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
  235. {
  236. // 处理读取的数据(此处代码省略)。
  237. }
  238. }
  239. Console.WriteLine("Get object:{0} succeeded", objectName);
  240. }
  241. catch (OssException ex)
  242. {
  243. Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
  244. ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
  245. }
  246. catch (Exception ex)
  247. {
  248. Console.WriteLine("Failed with error info: {0}", ex.Message);
  249. }
  250. }
  251. private static void streamProgressCallback(object sender, StreamTransferProgressArgs args)
  252. {
  253. System.Console.WriteLine("ProgressCallback - Progress: {0}%, TotalBytes:{1}, TransferredBytes:{2} ",
  254. args.TransferredBytes * 100 / args.TotalBytes, args.TotalBytes, args.TransferredBytes);
  255. }
  256. }
  257. }