AliyunOssHelper.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. using Aliyun.OSS;
  2. using Aliyun.OSS.Common;
  3. using Infrastructure;
  4. using System;
  5. using System.IO;
  6. namespace ZR.Common
  7. {
  8. public class AliyunOssHelper
  9. {
  10. static string accessKeyId = AppSettings.GetConfig("ALIYUN_OSS:KEY");
  11. static string accessKeySecret = AppSettings.GetConfig("ALIYUN_OSS:SECRET");
  12. static string endpoint = AppSettings.GetConfig("ALIYUN_OSS:REGIONID");
  13. static string bucketName1 = AppSettings.GetConfig("ALIYUN_OSS:bucketName");
  14. /// <summary>
  15. /// 上传到阿里云
  16. /// </summary>
  17. /// <param name="filestreams"></param>
  18. /// <param name="dirPath">存储路径 eg: upload/2020/01/01/xxx.png</param>
  19. /// <param name="bucketName">存储桶 如果为空默认取配置文件</param>
  20. public static System.Net.HttpStatusCode PutObjectFromFile(Stream filestreams, string dirPath, string bucketName = "")
  21. {
  22. OssClient client = new(endpoint, accessKeyId, accessKeySecret);
  23. if (string.IsNullOrEmpty(bucketName)) { bucketName = bucketName1; }
  24. try
  25. {
  26. dirPath = dirPath.Replace("\\", "/");
  27. PutObjectResult putObjectResult = client.PutObject(bucketName, dirPath, filestreams);
  28. // Console.WriteLine("Put object:{0} succeeded", directory);
  29. return putObjectResult.HttpStatusCode;
  30. }
  31. catch (OssException ex)
  32. {
  33. Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
  34. ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
  35. }
  36. catch (Exception ex)
  37. {
  38. Console.WriteLine("Failed with error info: {0}", ex.Message);
  39. }
  40. return System.Net.HttpStatusCode.BadRequest;
  41. }
  42. /// <summary>
  43. /// 删除资源
  44. /// </summary>
  45. /// <param name="dirPath"></param>
  46. /// <param name="bucketName"></param>
  47. /// <returns></returns>
  48. public static System.Net.HttpStatusCode DeleteFile(string dirPath, string bucketName = "")
  49. {
  50. if (string.IsNullOrEmpty(bucketName)) { bucketName = bucketName1; }
  51. try
  52. {
  53. OssClient client = new(endpoint, accessKeyId, accessKeySecret);
  54. DeleteObjectResult putObjectResult = client.DeleteObject(bucketName, dirPath);
  55. }
  56. catch (Exception ex)
  57. {
  58. Console.WriteLine(ex.Message);
  59. }
  60. return System.Net.HttpStatusCode.BadRequest;
  61. }
  62. }
  63. }